iOS技术分享、交流

UISearchController筛选功能

2016-11-25  本文已影响141人  楓葉乄神無月
import UIKit

class CategoryViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate {
    
    var mTableView:UITableView!
    var tableData = [Dictionary<String,String>]()
    var filteredData = [Dictionary<String,String>]()
    var resultSearchController = UISearchController()
    var bgBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        initData()
        initView()
    }
    
    override func viewWillAppear(animated: Bool) {
        if !bgBtn.hidden{
            bgBtn.hidden = true
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        if resultSearchController.active{
            resultSearchController.active = false
            resultSearchController.searchBar.removeFromSuperview()
        }
    }
    
    func initData(){
        //"地图展示", "聊天功能", "页面跳转", "自适应高度"
        let dict1 = Dictionary(dictionaryLiteral: ("code","01"),("name","地图展示"))
        tableData.append(dict1)
        let dict2 = Dictionary(dictionaryLiteral: ("code","02"),("name","聊天功能"))
        tableData.append(dict2)
        let dict3 = Dictionary(dictionaryLiteral: ("code","03"),("name","页面跳转"))
        tableData.append(dict3)
        let dict4 = Dictionary(dictionaryLiteral: ("code","04"),("name","自适应高度"))
        tableData.append(dict4)
    }
    
    func initView(){
        mTableView = UITableView(frame: CGRectMake(0, top_height, screen_width, screen_height - top_height - tabBar_height))
        mTableView.delegate = self
        mTableView.dataSource = self
        mTableView.tableFooterView = UIView()
        view.addSubview(mTableView)
        
        bgBtn = UIButton(frame: CGRectMake(0, top_height + 44, screen_width, screen_height))
        bgBtn.alpha = 0.4
        bgBtn.hidden = true
        bgBtn.backgroundColor = UIColor.grayColor()
        bgBtn.addTarget(self, action: "bgBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        self.view.addSubview(bgBtn)
        
        getSearchController()
    }
    
    //MARK: - 自定义方法
    func getSearchController(){
        
        if #available(iOS 9.0, *) {
            self.resultSearchController.loadViewIfNeeded()// iOS 9
        }
        
        // 实例化UISearchController,并且设置搜索控制器为本身TableView
        resultSearchController = UISearchController(searchResultsController: nil)
        
        //设置UISearchControllerDelegate delegate
        resultSearchController.delegate = self
        
        // 设置更新搜索结果的对象为self
        resultSearchController.searchResultsUpdater = self
        
        // 设置UISearchController是否在编辑的时候隐藏NavigationBar,默认为true
        resultSearchController.hidesNavigationBarDuringPresentation = false
        
        // 设置UISearchController是否在编辑的时候隐藏背景色,默认为true
        resultSearchController.dimsBackgroundDuringPresentation = false
        
        // 设置UISearchController搜索栏的UISearchBarStyle为Prominent
        resultSearchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
        
        // 设置UISearchController搜索栏的Size是自适应
        resultSearchController.searchBar.sizeToFit()
        
        // UISearchController可以设置在三个地方,任意选择一项
        // 1、设置navigationItem的titleView为UISearchController
        //self.navigationItem.titleView = resultSearchController.searchBar
        
        // 2、设置TableView的tableGHeaderView为controller.searchBar
        mTableView.tableHeaderView = resultSearchController.searchBar
        
        // 3、设置TableView的偏移量,使UISearchController默认就隐藏在Navigation下
        //mTableView.contentOffset = CGPointMake(0, CGRectGetHeight(resultSearchController.searchBar.frame))
    }
    
    func bgBtnClick(){
        resultSearchController.active  = false
        bgBtn.hidden = true
    }
    
    //MARK: - UITableViewDataSource
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if resultSearchController.active{
            return filteredData.count
        }else{
            return tableData.count
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "CellIdentifier"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier)
        if cell == nil{
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
        }
        if resultSearchController.active{
            cell!.textLabel?.text = filteredData[indexPath.row]["name"]
        }else{
            cell!.textLabel?.text = tableData[indexPath.row]["name"]
        }
        return cell!
    }
    
    //MARK: - UITableViewDelegate
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        var selectCode:String!;
        var nextPageTitle:String!
        if resultSearchController.active{
            selectCode = filteredData[indexPath.row]["code"]
            nextPageTitle = filteredData[indexPath.row]["name"]
        }else{
            selectCode = tableData[indexPath.row]["code"]
            nextPageTitle = tableData[indexPath.row]["name"]
        }
        switch selectCode {
        case "01":
            let mapVC = MapViewController()
            mapVC.title = nextPageTitle
            mapVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(mapVC, animated: true)
        case "02":
            CDChatManager.sharedManager().openWithClientId("你好", callback: { (result: Bool, error: NSError!) -> Void in
                if (error == nil) {
                    let chatListVC = ChatListViewController()
                    chatListVC.title = nextPageTitle
                    chatListVC.hidesBottomBarWhenPushed = true
                    self.navigationController?.pushViewController(chatListVC, animated: true)
                }
            })
        case "03":
            let firstVC = FirstViewController()
            firstVC.title = nextPageTitle
            self.navigationController?.pushViewController(firstVC, animated: true)
        case "04":
            let autoSizeVC = AutoSizeViewController()
            autoSizeVC.title = nextPageTitle
            autoSizeVC.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(autoSizeVC, animated: true)
        default:
            break
        }
    }
    
    //MARK: - UISearchControllerDelegate
    func didPresentSearchController(searchController: UISearchController) {
        //隐藏searchBar右侧的取消按钮
        searchController.searchBar.showsCancelButton = false
    }
    
    //MARK: - UISearchResultsUpdating
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        if searchController.searchBar.text == ""{
            // 当搜索框内容为空时,设置bgView.hidden为false
            bgBtn.hidden = false
            filteredData = tableData
        }else{
            // 当搜索框内容不为空时,设置bgView.hidden为true
            bgBtn.hidden = true
            
            // 删除filteredData里的所有元素,并且默认的保存为false
            filteredData.removeAll(keepCapacity: false)
            
            filteredData = self.tableData.filter({ (dict) -> Bool in
                let stringMatch = dict["name"]?.rangeOfString(searchController.searchBar.text!)
                return stringMatch != nil
            })
            
            /** 对数组进行筛选
            // 输入筛选文本,获取之后会自动去内存中搜索关键字,SELF CONTAINS[c]
            let searchPredicate = NSPredicate(format: "SELF CONTAINS[C] %@", searchController.searchBar.text!)
            // 从tableData中筛选输入的关键字
            let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
            // 再把筛选出来的关键字加入到filteredData中
            filteredData = array as! [String]
            **/
        }
        
        // 刷新TableView
        mTableView.reloadData()
    }
}
上一篇 下一篇

猜你喜欢

热点阅读