UITableView中有一个很是好用的功能:索引,经过索引咱们能够对Cell进行快速的查找,让整个表格变的更有条理,这里咱们来实现一下相似通信录的索引功能数组
var sectionArray:[String]?
numberOfSectionsInTableView为索引的数量
titleForHeaderInSection获取具体Section的标题
sectionIndexTitlesForTableView获取储存索引的数组app
//索引数量 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!) } }