UISearchController 搜尋控制器


加入協定

class ViewControllertest: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchResultsUpdating {

宣告資料

var search = UISearchController()
var tableview = UITableView()
var names = ["Bill", "John", "Harry", "Alex", "Jenny", "Arno", "Bert", "Chad", "Dave", "Eden"]
var searches: [String] = []
let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height

viewDidLoad

view.backgroundColor = .lightGray
    // 結果顯示在相同ViewController
    search = UISearchController(searchResultsController: nil)
    // 委任
    search.searchBar.delegate = self
    search.searchResultsUpdater = self
    // style
    search.searchBar.searchBarStyle = .prominent
    /*
     .default       預設
     .minimal       白色輸入欄
     .prominent     暗色輸入欄
     */
    // 提示文字
    search.searchBar.placeholder = "點擊搜尋"
    // 取消按鈕
    search.searchBar.setValue("取消",
                              forKey:"_cancelButtonText")
    // 文字顏色
    search.searchBar.tintColor = .white
    // 背景顏色
    search.searchBar.barTintColor = .lightGray
    // 背景圖片(除黑線)
    search.searchBar.backgroundImage = UIImage()
    // 隱藏導覽列
    search.hidesNavigationBarDuringPresentation = true
    // 暗化背景
    search.dimsBackgroundDuringPresentation = false
    // 鍵盤樣式
    search.searchBar.keyboardType = .default
    /*
    UIKeyboardType
     .default                   預設
     .numbersAndPunctuation     數字, 符號
     .numberPad                 數字
     .decimalPad                數字(.)
     .phonePad                  數字(+, *, #)
     .namePhonePad              英文
     .URL                       英文(., /, .com)
     .emailAddress              英文(@, .)
     .twitter                   英文(@, #)
     .asciiCapable              英文(不能切換語言)
     .webSearch                 英文(return 鍵為go)
     */
    // return 鍵樣式
    search.searchBar.returnKeyType = .search
    /*
    UIReturnKeyType  
     default           return
     go                Go
     join              Join
     next              Next
     route             Route
     send              Send
     search            Search
     google            Search
     yahoo             Search
     done              Done
     emergencyCall     Emergency Call
     continue          Continue
     */

    tableview = UITableView(frame: CGRect(x: 0,
                                          y: 0,
                                          width: WIDTH,
                                          height: HEIGHT),
                            style: .plain)
    tableview.delegate = self
    tableview.dataSource = self
    tableview.register(UITableViewCell.self,
                       forCellReuseIdentifier: "cell")
    tableview.backgroundColor = .lightGray
    tableview.separatorStyle = .singleLine
    tableview.separatorColor = .lightGray
    tableview.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
    // 加入搜尋欄
    tableview.tableHeaderView = search.searchBar
    tableview.tableFooterView = UIView(frame: .zero)
view.addSubview(tableview)

UITableViewDelegate、UITableViewDatasource

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return search.isActive ? searches.count : names.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    if cell == nil {
        cell = UITableViewCell(style: .default,
                               reuseIdentifier: "cell")
    }
    cell?.textLabel?.text = search.isActive ? "\(searches[indexPath.row])" : "\(names[indexPath.row])"

    return cell!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, 
                          animated: true)
}

建立更新搜尋動作

func updateSearchResults(for searchController: UISearchController) {
    if let results = search.searchBar.text {
        searches = names.filter { (name) -> Bool in
            return name.contains(results)
        }
    }
    tableview.reloadData()
}

results matching ""

    No results matching ""