UISearchController篩選功能

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(){
        //"地圖展示", "聊天功能", "頁面跳轉(zhuǎn)", "自適應(yīng)高度"
        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","頁面跳轉(zhuǎn)"))
        tableData.append(dict3)
        let dict4 = Dictionary(dictionaryLiteral: ("code","04"),("name","自適應(yīng)高度"))
        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,并且設(shè)置搜索控制器為本身TableView
        resultSearchController = UISearchController(searchResultsController: nil)
        
        //設(shè)置UISearchControllerDelegate delegate
        resultSearchController.delegate = self
        
        // 設(shè)置更新搜索結(jié)果的對象為self
        resultSearchController.searchResultsUpdater = self
        
        // 設(shè)置UISearchController是否在編輯的時候隱藏NavigationBar躺盛,默認為true
        resultSearchController.hidesNavigationBarDuringPresentation = false
        
        // 設(shè)置UISearchController是否在編輯的時候隱藏背景色输吏,默認為true
        resultSearchController.dimsBackgroundDuringPresentation = false
        
        // 設(shè)置UISearchController搜索欄的UISearchBarStyle為Prominent
        resultSearchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
        
        // 設(shè)置UISearchController搜索欄的Size是自適應(yīng)
        resultSearchController.searchBar.sizeToFit()
        
        // UISearchController可以設(shè)置在三個地方,任意選擇一項
        // 1蹦骑、設(shè)置navigationItem的titleView為UISearchController
        //self.navigationItem.titleView = resultSearchController.searchBar
        
        // 2、設(shè)置TableView的tableGHeaderView為controller.searchBar
        mTableView.tableHeaderView = resultSearchController.searchBar
        
        // 3控乾、設(shè)置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右側(cè)的取消按鈕
        searchController.searchBar.showsCancelButton = false
    }
    
    //MARK: - UISearchResultsUpdating
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        if searchController.searchBar.text == ""{
            // 當(dāng)搜索框內(nèi)容為空時拧咳,設(shè)置bgView.hidden為false
            bgBtn.hidden = false
            filteredData = tableData
        }else{
            // 當(dāng)搜索框內(nèi)容不為空時图甜,設(shè)置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
            })
            
            /** 對數(shù)組進行篩選
            // 輸入篩選文本,獲取之后會自動去內(nèi)存中搜索關(guān)鍵字黑毅,SELF CONTAINS[c]
            let searchPredicate = NSPredicate(format: "SELF CONTAINS[C] %@", searchController.searchBar.text!)
            // 從tableData中篩選輸入的關(guān)鍵字
            let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
            // 再把篩選出來的關(guān)鍵字加入到filteredData中
            filteredData = array as! [String]
            **/
        }
        
        // 刷新TableView
        mTableView.reloadData()
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嚼摩,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子矿瘦,更是在濱河造成了極大的恐慌枕面,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,729評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件缚去,死亡現(xiàn)場離奇詭異潮秘,居然都是意外死亡,警方通過查閱死者的電腦和手機易结,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,226評論 3 399
  • 文/潘曉璐 我一進店門枕荞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人搞动,你說我怎么就攤上這事躏精。” “怎么了鹦肿?”我有些...
    開封第一講書人閱讀 169,461評論 0 362
  • 文/不壞的土叔 我叫張陵矗烛,是天一觀的道長。 經(jīng)常有香客問我狮惜,道長高诺,這世上最難降的妖魔是什么碌识? 我笑而不...
    開封第一講書人閱讀 60,135評論 1 300
  • 正文 為了忘掉前任碾篡,我火速辦了婚禮,結(jié)果婚禮上筏餐,老公的妹妹穿的比我還像新娘开泽。我一直安慰自己,他們只是感情好魁瞪,可當(dāng)我...
    茶點故事閱讀 69,130評論 6 398
  • 文/花漫 我一把揭開白布穆律。 她就那樣靜靜地躺著,像睡著了一般导俘。 火紅的嫁衣襯著肌膚如雪峦耘。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,736評論 1 312
  • 那天旅薄,我揣著相機與錄音辅髓,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛洛口,可吹牛的內(nèi)容都是我干的矫付。 我是一名探鬼主播,決...
    沈念sama閱讀 41,179評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼第焰,長吁一口氣:“原來是場噩夢啊……” “哼买优!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起挺举,我...
    開封第一講書人閱讀 40,124評論 0 277
  • 序言:老撾萬榮一對情侶失蹤杀赢,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后豹悬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體葵陵,經(jīng)...
    沈念sama閱讀 46,657評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,723評論 3 342
  • 正文 我和宋清朗相戀三年瞻佛,在試婚紗的時候發(fā)現(xiàn)自己被綠了脱篙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,872評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡伤柄,死狀恐怖绊困,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情适刀,我是刑警寧澤秤朗,帶...
    沈念sama閱讀 36,533評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站笔喉,受9級特大地震影響取视,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜常挚,卻給世界環(huán)境...
    茶點故事閱讀 42,213評論 3 336
  • 文/蒙蒙 一作谭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧奄毡,春花似錦折欠、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,700評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至盗忱,卻和暖如春酱床,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背趟佃。 一陣腳步聲響...
    開封第一講書人閱讀 33,819評論 1 274
  • 我被黑心中介騙來泰國打工扇谣, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留慷垮,地道東北人。 一個月前我還...
    沈念sama閱讀 49,304評論 3 379
  • 正文 我出身青樓揍堕,卻偏偏與公主長得像料身,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子衩茸,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,876評論 2 361

推薦閱讀更多精彩內(nèi)容