# iOS | Swift/--- SwiftUI

SwiftUI Tutorials_ Search Bar

jiniz.ll 2022. 11. 15. 16:59

 

KavSoft 채널의 튜토리얼에 대한 내용을 하나씩 해보면서 SwiftUI에 대해 공부해보려고 합니ㅏㄷ.

따라서 이 글은 위 튜토리얼에 대한 정리 글입니다.

 

  • Xcode 14.1
  • iOS 16.1

 

** 코드는 일부 수정하여 영상과 조금 다를 수 있습니다.

 

이번 내용은 SwiftUI에서 SearchBar를 사용하기 위한 방법을 학습합니다.

SwiftUI에서 기본적으로 SearchBar를 제공해주지 않기 때문에 직접 SearchBar를 구현하거나 UISearchBar를 사용하여 구현할 수 있습니다.

 

이 영상에서는 UISearchBar를 사용하여 구현하는 방법을 알려주지만 직접 구현하는 방법도 함께 작성해보려 합니다.

 

1. UISearchBar 사용하기

UIKit에서 제공되는 뷰를 SwiftUI를 사용하기 위해서는 공통적으로 UIViewRepresentable을 채택하는 뷰를 추가해줍니다.

이때 makeUIView()updateUIView() 메서드는 필수적으로 추가합니다. makeUIView()는 뷰를 보여줄 때 한 번만 호출하게 됩니다.

 

또한 UIKit 에서 SwiftUI에 데이터를 전달하기 위해 Coordinator를 사용하는데 이 때 관련된 메서드들을 정의한다.

Coordinator를 사용할 때는 makeCoordinator() 메서드도 필수로 구현해주어야 한다.

struct SearchView: UIViewRepresentable {
    
    @Binding var text: String
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }
    
    func makeUIView(context: Context) -> UISearchBar {
        let searchBar = UISearchBar()
        searchBar.barStyle = .default
        searchBar.autocapitalizationType = .none
        searchBar.delegate = context.coordinator
        return searchBar
    }
    
    func updateUIView(_ uiView: UISearchBar, context: Context) {
        
    }
    
    class Coordinator: NSObject, UISearchBarDelegate {
        
        var parent: SearchView
        
        init(parent: SearchView) {
            self.parent = parent
        }
        
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            parent.text = searchText
        }
    }
}

 

SearchBar 테스트를 위한 임시 데이터를 추가하고 searchBar에 입력될 텍스트를 저장할 text 변수를 추가합니다.

VStack을 사용하여 위에서 추가한 SearchView와 데이터 목록을 보여줄 List를 보여줍니다. 입력한 검색어를 필터링하기 위한 코드를 추가하여 구현할 수 있습니다.

struct SearchBarView: View {
    
    @State var datas = ["hello", "Hi", "Welcome", "World", "swiftUI", "My name"]
    @State var text = ""
    
    var body: some View {
        
        VStack {
            SearchView(text: $text)
            
            List(datas.filter{ text == "" ? true :  $0.localizedCaseInsensitiveContains(text)}, id: \.self) { data in
                Text(data).fontWeight(.heavy)
            }
        }
    }
}

 

localizedCaseInsensitiveContains(_:)

대소문자 구분 없이 문자열 내에 입력한 문자열이 포함되어 있는지 체크하는 메서드

 

2. SwiftUI로 직접 구현하기 (강의에 없는 내용)

UISearchBar와 유사하게 직접 SearchBar 를 구현합니다. 사실 필터링 과정은 위와 동일하므로 생략합니다.

struct SearchBar: View {
    
    @Binding var text: String
    
    var body: some View {
        HStack {
            Image(systemName: "magnifyingglass")
            
            TextField("Search", text: $text)
                .foregroundColor(.primary)
            
            if !text.isEmpty {
                Button {
                    text = ""
                } label: {
                    Image(systemName: "xmark.circle.fill")
                }
            }
        }
        .padding(8)
        .foregroundColor(.secondary)
        .background(Color(.secondarySystemBackground))
        .cornerRadius(10.0)
    }
}

 

 

'# iOS | Swift > --- SwiftUI' 카테고리의 다른 글

[공식문서] SwiftUI_ ContextMenu  (0) 2022.11.16
SwiftUI Tutorials_ Context Menu  (0) 2022.11.16
SwiftUI Tutorials_ TopBar Style TabView  (0) 2022.11.09
SwiftUI Tutorials_ TabView  (0) 2022.10.31
SwiftUI Tutorials_ Json Parsing  (0) 2022.10.26