iOS Tableview实现searchBar和字母索引

在开发过程中,当app需要显示大量用户的时候,想要查找到某一个用户显然没有那么容易。参考iOS原生的通讯录我们可以发现,查找用户可以用searchBar来精确匹配字段,也可以用sectionIndex来定位一个范围。

searchBar的代理方法

//当按下搜索按钮时进入这个方法
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        self.view.endEditing(true)

        searchNumAry = NSMutableArray()
        
        let ary:NSArray = userAry as! NSArray
        
        //循环遍历(当用户量非常大的时候就需要用到算法了,不然会卡线程)
        for i in 0 ..< ary.count {
            
            let dic:NSDictionary = ary[i] as! NSDictionary
            
            let str = (dataDic["name"]) as! String
            
            //匹配字段
            if (str.range(of: searchBar.text!) != nil) {

                //匹配到的用户下标记下来
                searchNumAry.add(NSNumber.init(value: i))

            }
        }
        
        print(searchNumAry)
        
        self.tableview.reloadData()
 }
    
//当输入框字段改变时进入这个方法
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        //判断搜索栏输入框是否有文字
        if (searchBar.text == "") {
            self.tableview.reloadData()
        }
}

下面是sectionIndex的用法

//设置索引的标题
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if sectionAry.count != 0 {
            return sectionAry
        } else {
            return [""]
        }
}

//设置section的标题
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if sectionAry.count != 0 {
            if self.searchBar.text == "" {
                return sectionAry[section]
            } else {
                return ""
            }
        } else {
            return ""
        }
}

func numberOfSections(in tableView: UITableView) -> Int {
        if self.searchBar.text == "" {
            if sectionAry.count != 0 {
                return sectionAry.count
            } else {
                return 0
            }
        } else {
            return 1
        }
    }


实现了上面的代码后,在这两个方法中做相应的判断修改即可得到想要的效果了

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容