UITableView基礎[ 5 ] 右側索引的實現

介紹

UITableView中有一個很是好用的功能:索引,經過索引咱們能夠對Cell進行快速的查找,讓整個表格變的更有條理,這裏咱們來實現一下相似通信錄的索引功能數組

實現

首先咱們定義一個數組用於儲存Section

var sectionArray:[String]?

實現UITableView有關索引的部分代理方法

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!)
    }
}
相關文章
相關標籤/搜索