UITableViewCell一些基本用法

屏幕快照 2016-11-29 下午4.51.21.png

# UITableViewCell一些基本用法
一、
1:UITableViewController繼承自UIViewController,自帶一個(gè)tableview
2:self.view不是UIView而是UITableView
3:datasource和delegate默認(rèn)都是self(UITableViewController)
4:開發(fā)中只需要建立UITableViewController子類。就會(huì)幫助我們實(shí)現(xiàn)datasource和delegate協(xié)議中的一些相關(guān)的方法,比如tableview編輯(增加,刪除,移動(dòng)),以及多少的分區(qū),每個(gè)分區(qū)有多少個(gè)cell和返回cell視圖的方法,當(dāng)你需要的時(shí)候只需要打開相應(yīng)的注視即可。
二、
tableView編輯的步驟:
1.讓tableView出于編輯狀態(tài)
2.設(shè)置哪些cell可以編輯
3.設(shè)置編輯的樣式(刪除,插入)
4.提交編輯操作(1.先修改數(shù)據(jù)源,2.更新UI)
三、
tableView移動(dòng)的步驟:
1.讓tableView出于編輯狀態(tài)
2.設(shè)置哪些cell可以編輯
3.提交移動(dòng)結(jié)果(1.只需要更新數(shù)據(jù)源即可)

 //重用標(biāo)識(shí)
    let identifier = "cell"
    
    //聯(lián)系人字典屬性 var dic:[String:[String]]
    var contactSource = [
        "W":["王哲磊","王浩","王樂","王晨陽"],
        "C":["陳揚(yáng)","陳芮"],
        "B":["邊文達(dá)","寶音","白婧"],
        "L":["李玲","劉二蛋","劉婧","劉福宏"]
    ]
    

    //存放排好序的key值
    var keysArray:[String]?
override func viewDidLoad() {
        super.viewDidLoad()

        //取出字典contactArray中的key值
        let keys = self.contactSource.keys
        //排序后賦值給keysArray
        keysArray = keys.sorted()
       //print(keysArray)
        
        //注冊(cè)cell
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: identifier)
        
        //1.讓tableView出于編輯狀態(tài)
         self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

此方法必須打開

override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

返回分區(qū)個(gè)數(shù)

 override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        //分組的個(gè)數(shù) = 字典中鍵值對(duì)的個(gè)數(shù)
        //分組的個(gè)數(shù) = 存放排好序key值數(shù)組元素個(gè)數(shù)
        return contactSource.count
    }

返回cell個(gè)數(shù)

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 先取出排好序key值數(shù)組的對(duì)應(yīng)分區(qū)的key值
        let key = keysArray?[section]
        
        let group = contactSource[key!]
        
        return (group?.count)!
    }

返回cell

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)

      //取出字典中key值對(duì)應(yīng)數(shù)組元素的值賦值給textLabel
        let key = keysArray?[indexPath.section]
        //根據(jù)key值取出字典中的value值
        let group = contactSource[key!]
        //根據(jù)cell的下標(biāo)取出數(shù)組中對(duì)應(yīng)位置的元素
        let name = group?[indexPath.row]
        cell.textLabel?.text = name

        return cell
    }

區(qū)頭標(biāo)題

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
     
        return "\(keysArray![section])"
    }

索引列表

override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return keysArray
    }

設(shè)置哪些cell可以編輯

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        
        if indexPath.section < 2{
           return true
        }
        return false
    }

設(shè)置編輯的樣式(刪除,插入)

override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        if indexPath.section == 0 {
            return .delete
        }else if indexPath.section == 1 {
            return .insert
        }
        return .none
        
    }

提交編輯操作(1.先修改數(shù)據(jù)源,2.更新UI

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
       
        //先取出選中cell所在的分區(qū)對(duì)應(yīng)的key值
        let key = keysArray?[indexPath.section]
        //根據(jù)key值取出對(duì)應(yīng)的value值數(shù)組
        var group = contactSource[key!]
        
        if editingStyle == .delete {
           
            //刪除整個(gè)分區(qū)
            if group?.count == 1{
               //1.刪除字典中的鍵值對(duì)
                contactSource.removeValue(forKey: key!)
                //2.刪除排好序的keysArray數(shù)組中的元素
                keysArray?.remove(at: indexPath.section)
                //3.更新UI
                let set = NSIndexSet(index: indexPath.section)
                tableView.deleteSections(set as IndexSet, with: .left)
                
            }else{//一條條的刪除cell
                //先修改數(shù)據(jù)源
                group?.remove(at: indexPath.row)
                //刪除之后重新為字典中values賦值(group刪除并沒有將字典中的數(shù)組內(nèi)容刪除)
                contactSource[key!] = group
                //更新UI
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            
        } else if editingStyle == .insert {
            
            //準(zhǔn)備要插入的數(shù)據(jù)
            let name = "逗逼"
            //1.先修改數(shù)據(jù)源
            group?.append(name)
            //2.重新對(duì)字典的鍵值對(duì)賦值
            contactSource[key!] = group
            //3.更新UI
            tableView.insertRows(at: [indexPath], with: .right)
            //4.讓tableView重新加載數(shù)據(jù)
            tableView.reloadData()
        }    
    }

刪除按鈕的文字

override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "刪除"
    }

設(shè)置哪些cell可以移動(dòng)

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
      return true
    }

提交移動(dòng)結(jié)果(只需要更新數(shù)據(jù)源即可)

override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

        //修改數(shù)據(jù)源
        let key = keysArray?[fromIndexPath.section]
        var group = contactSource[key!]
        //取出數(shù)組中原位置的元素
        let name = group?[fromIndexPath.row]
        //刪除數(shù)組中原來位置的元素
        group?.remove(at: fromIndexPath.row)
        //插入數(shù)組中新的位置
        group?.insert(name!, at: to.row)
        //重新對(duì)字典中key值對(duì)應(yīng)的value值賦值
        contactSource[key!] = group
    }

/// Description:限制跨分區(qū)移動(dòng)
///
/// - Parameters:參數(shù)
/// - tableView: tableView對(duì)象,代理的委托人
/// - sourceIndexPath: 移動(dòng)之前cell的位置
/// - proposedDestinationIndexPath: 移動(dòng)之后cell的位置
/// - Returns: cell移動(dòng)之后最終的位置

override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
        //根據(jù)分區(qū)的下標(biāo)判斷是否允許移動(dòng),當(dāng)前后的位置在同一個(gè)分區(qū),允許移動(dòng)返回移動(dòng)之后的位置。當(dāng)前后的位置不在同一個(gè)分區(qū),允許移動(dòng)返回移動(dòng)之前的位置。
        if sourceIndexPath.section == proposedDestinationIndexPath.section {
            return proposedDestinationIndexPath
        }else{
            return sourceIndexPath
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容