UITableView基础[ 5 ] 右侧索引的实现

介绍

UITableView中有一个非常好用的功能:索引,通过索引我们可以对Cell进行快速的查找,让整个表格变的更有条理,这里我们来实现一下类似通讯录的索引功能

实现

首先我们定义一个数组用于储存Section

    var sectionArray:[String]?

实现UITableView有关索引的部分代理方法

numberOfSectionsInTableView为索引的数量
titleForHeaderInSection获取具体Section的标题
sectionIndexTitlesForTableView获取储存索引的数组

//索引数量
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    if sectionArray == nil{
        return 0
    }
    return sectionArray!.count
}

//Section的标题
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return sectionArray![section]
}

//获取储存索引的数组
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
    if sectionArray == nil{
        return nil
    }
    return sectionArray!
}
实现了这几个代理方法后,理论上就可以显示出索引了

实现索引数组的自动更新

 索引数组应该随着数据数组的改变而改变
 设计通过数据数组返回索引数组的函数
    /**
    根据UITableView Data数组寻找索引并添加进索引数组
    
    - parameter DataArray: UITableView数据数组
    
    - returns: 索引数组
    */
    func searchForSection(DataArray:[item])->[String]{
        var stringDataArray = [String]()
        for var i=0;i<DataArray.count;++i{
            stringDataArray.append(DataArray[i].Name!)
        }
        var array=[String]()
        for str in stringDataArray{
            //查重,避免添加错误的索引
            var flag = false
            for existSection in array{
                if String(str[str.startIndex]) == existSection {
                    flag = true
                }
            }
            if flag == false{
                array.append(String(str[str.startIndex]))
            }
        }
        return array
    }

有了这段代码我们就可以根据数据数组生成索引数组了
随后我们将索引数组的更新放进数据数组的属性的didSet方法,这样实现了索引数组的随时更新

var infoArray:[item]?{
    didSet{
        sectionArray = searchForSection(infoArray!)
    }
}
    原文作者:Hydrogen
    原文地址: https://segmentfault.com/a/1190000003869087
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞