0%

iOS开发:UISearchController使用详解

UISearchController一般用在搜索功能,通常的交互是在ViewController1上有个SearchBar,不可输入,点击searchBar,展示ViewController2,此时searchBar变成可编辑状态,输入keywork,在ViewController2里展示搜索提示,searchBar上有Cancel按钮,点击后返回ViewController1。很常见的交互,某些PD偷懒,不考虑Android的特性,让Android版本也实现同样的效果,虽然技术上也能实现,但是,这是iOS的特性,iOS自带控件,对一名有情怀的Android开发来说,就是摧残,包括精神和肉体… 代码来自极客学院视频教程,图书管理项目。虽然我是新手,但感觉老师某些地方代码还是有点问题,擅自改动了一些些,另外,要吐槽一下,作为年费VIP,我提的问题快超过24小时了没有任何答复…

显示搜索提示的SearchViewController:

import UIKit

class SearchViewController: UIViewController,UISearchResultsUpdating, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
weak var homeController: HomeViewController!

var searchController: UISearchController!

var searchTitles = \[String\]()
var books = \[Book\]()
override func awakeFromNib() {
    searchController = UISearchController(searchResultsController: self)
    searchController.searchResultsUpdater = self
    //hint
    searchController.searchBar.placeholder = "搜索图书"
    //光标和取消按钮的颜色
    searchController.searchBar.tintColor = UIColor.whiteColor()
    //删除默认灰色背景
    searchController.searchBar.subviews\[0\].subviews\[0\].removeFromSuperview()
}

func updateSearchResultsForSearchController(searchController: UISearchController) {
    //获取输入的关键字,过滤空白后,调接口
    if let tag = searchController.searchBar.text?.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet()) where !tag.isEmpty {
        HomeDataHandler.searchBook(tag, start: 0) { (books) -> Void in
            //接口返回,显示
            self.books = books!
            self.tableView.reloadData()
        }
    }
}

override func viewDidLoad() {
    tableView.dataSource = self
    tableView.delegate = self
    
}

//MARK: - UITableView -
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return books.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("searchCell")
    let book = books\[indexPath.row\]
    if cell == nil {
        cell = UITableViewCell()
    }
    cell?.textLabel?.text = book.title
    return cell!
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var book = books\[indexPath.row\]
    searchController.active = false
}

}

界面很简单,就一个UITableView,但是得在顶上留点位置给searchBar,默认是44

要调用的ViewController里,顶部给SearchBar留Container View,下面的例子里叫searchView:

override func viewDidLoad() {
    super.viewDidLoad()
   
    let searchViewController = storyboard?.instantiateViewControllerWithIdentifier("searchController") as! SearchViewController
    searchViewController.homeController = self
    //把searchBar加上
    searchView.addSubview(searchViewController.searchController.searchBar)
    
}