수많은 앱에서는 검색하는 기능을 구현해야 하는 경우가 있습니다

 

코드

코드는 엄청 간단합니다.

 

 

struct SearchBar: View {
    
    @Binding var text: String

    var body: some View {
        HStack {
            HStack {
                Image(systemName: "magnifyingglass")

                TextField("게임, 시리즈, 영화를 검색하세요...", text: $text)
                    .foregroundColor(.primary)

                if !text.isEmpty {
                    Button(action: {
                        self.text = ""
                    }) {
                        Image(systemName: "xmark.circle.fill")
                    }
                } else {
                    EmptyView()
                }
            }
            .padding(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8))
            .foregroundColor(.secondary)
            .background(Color(.secondarySystemBackground))
            .cornerRadius(5.0)
        }
        .padding(.horizontal)
    }
}

 

이후 다음과 같이 사용될 수 있습니다

struct MovieSearchView: View {
    
    @State private var searchText = ""
    
    var body: some View {
        SearchBar(text: $searchText)
        Text("Hello, World!")
    }
}
ytw_developer