안녕하세요, 오늘은 저희가 자주사용하는 서치바를 Navigation Item에 추가하는 실습을 해 보겠습니다.
일단 기본적으로 UISearchController 객체를 생성해 줘야 겠죠.
아래와 같은 코드로 생성해 줍니다.
let searchController = UISearchController(searchResultsController: nil)
그리고 이제 서치컨트롤러를 navigation controller에 대입해 줘야 하는데요, navigation item이 가지고 있는 searchController 속성을 사용해서 assign 해 줍니다.
navigationItem.searchController = searchController
이제 delegate pattern 구현을 위해 UISearchBarDelegate 프로토콜을 채택해 주고, 다음 순서로 delegate를 현재 View Controller로 지정해 줍니다.
주의할 사항은 USSearchController 가 아닌 searchController.searchBar.delegate를 self로 대입해 줘야 한다는 것입니다.
searchController.searchBar.delegate = self
그 다음엔 아래 메소드를 사용하여 저희가 원하는 방식으로 서치바에 입력한 내용들을 출력할 수 있습니다.
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
}
전체코드
import UIKit
class ViewController: UIViewController, UISearchBarDelegate {
let searchController = UISearchController(searchResultsController: nil)
override func viewDidLoad() {
super.viewDidLoad()
// 아래 코드로 서치컨트롤러 삽입
navigationItem.searchController = searchController
// Do any additional setup after loading the view.
searchController.searchBar.delegate = self
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
print(searchText)
}
}
'iOS' 카테고리의 다른 글
iOS - Alamofire (0) | 2020.08.04 |
---|---|
iOS - UIImageView를 활용한 Animation 구현 (0) | 2020.07.17 |
iOS - IBOutlet & IBAction (0) | 2020.07.16 |
iOS - TableView Dynamic Cell (0) | 2020.07.14 |
Source Control with Xcode (0) | 2020.07.09 |