iOS通讯录(带搜索框, 索引条)swift

先上代码

import UIKit
class ContactViewController: OABaseViewController {

    var tableView = UITableView()
    var searchBar = UISearchBar()
    
    var datalist = ["张三", "李四", "王五", "王朝", "阿拉斯加", "哈士奇", "马汉", "张龙", "赵虎",  "长江", "长江1号", "&*>?", "弯弯月亮", "that is it ?", "山水之间", "倩女幽魂", "疆土无边"]
    var searchlist = [String]()
    var allDataSource = NSDictionary()
    var indexDataSource = [Any]()
    
    var isSearch : Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
       
        setupUI()
        processData()
    }

    func processData() {
        allDataSource = HCSortString.sortAndGroup(for: datalist, propertyName: "name") //字典数组
        indexDataSource = HCSortString.sort(forStringAry: allDataSource.allKeys) as! [Any]
    }
    
    func setupUI() {
        let tableView1 = UITableView(frame: CGRect(0, 60, screenWidth, screenHeight-64-60-49), style: .plain)
        tableView1.delegate = self
        tableView1.dataSource = self
        tableView1.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20)
        tableView1.register(ContactCell.self, forCellReuseIdentifier: "contactCellId")
        tableView = tableView1
//        tableView.sectionHeaderHeight = 28
        tableView.sectionFooterHeight = 0
        view.addSubViews(views: [tableView, searchBar])
        
        searchBar.frame = CGRect(0, 0, screenWidth, 60)
        searchBar.delegate = self
        searchBar.placeholder = "搜索"
        searchBar.showsCancelButton = false
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}

extension ContactViewController : UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if !isSearch {
            return indexDataSource.count
        }else{
            return 1
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if !isSearch {
            let values = allDataSource.object(forKey: indexDataSource[section]) as! NSArray
            return values.count
        }else{
            return searchlist.count
        }
    }
    
    //通讯录姓名首字母
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(0,0,0,28))
        view.backgroundColor = UIColor("#f2f2f2")
        let titleLabel = UILabel()
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(20)
        }
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.textColor = UIColor("#000000")
        if !isSearch {
            titleLabel.text = indexDataSource[section] as? String
        }else{
            titleLabel.text = ""
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if !isSearch {
            return 28
        }else{
            return 0
        }
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactCellId") as! ContactCell
        if !isSearch {
            let values = allDataSource.value(forKey: indexDataSource[indexPath.section] as! String) as! NSArray
            cell.nameLabel.text = values[indexPath.row] as? String
        }else{
            cell.nameLabel.text = searchlist[indexPath.row]
        }
        return cell
    }
    
    //右侧索引列表
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        if !isSearch {
            return indexDataSource as? [String]
        }else{
            return nil
        }
    }
    
    //索引点击事件
    func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
        tableView.scrollToRow(at: NSIndexPath.init(row: 0, section: index) as IndexPath , at: .top, animated: true)
        return index
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchlist.removeAll()
        var arr = [String]()
        arr = HCSortString.getAllValues(fromDict: allDataSource as! [AnyHashable : Any]) as! [String]
        if searchText.length == 0 {
            isSearch = false
            searchlist += arr
        }else{
            isSearch = true
           // 搜索数组,返回新的数组。
            arr = ZYPinYinSearch.search(withOriginalArray: arr, andSearchText: searchBar.text, andSearchByPropertyName: "name") as! [String]
            searchlist += arr
        }
        tableView.reloadData()
    }
    
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = true
        UIView.animate(withDuration: 0.3) {
//            self.navigationController?.navigationBar.isHidden = true
//            searchBar.frame = CGRect(0, 20, screenWidth, 60)
        }
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { //不会走textDidChange方法
        searchBar.showsCancelButton = false
        isSearch = false
        searchBar.text = ""
        searchBar.resignFirstResponder()
        tableView.reloadData()
    }
}

这种写法适合搜索条不动的情况, 大体思路是:

  1. 通讯录其实是一个字典, key是首字母, 即tableview的header的title, value是每个字母下面对应的名字
  2. value是一个数组, 所以在拿到所有通讯录人名的情况下, 先按照首字母分别添加到value的array当中, 再按照字母排序在array内排序
  3. 搜索的实现思路很简单, 是将汉字全部转化为拼音, 用ZYPinYinSearch的类方法直接实现搜索
  4. 索引条只需要引用两个tableview的代理方法即可实现,
  5. 设置heightForHeaderInSection的时候请按照文中的方法, 否则效果可能会不一样
  6. 本文主要借鉴 https://github.com/honeycao/HCSortAndSearchDemo ,只是基于swift, 将demo中的HCSortAndSearch文件夹拖到项目中即可, 引入#import "ZYPinYinSearch.h" #import "HCSortString.h" 这两个头文件

你可能感兴趣的:(iOS通讯录(带搜索框, 索引条)swift)