UITableView


import UIKit
// 添加兩個代理協議:表格視圖代理協議 UITableViewDelegate;表格視圖數據源協議 UITableViewDataSource
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // 代理方法,用來設置表格視圖,返回單元格行數
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weeks.count
    }
    
    // 代理方法,用來設置表格行的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    // 代理方法,用來初始化或復用表格視圖中的單元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        // 索引路徑用來標識單元格在表格中的位置。它有section(段落)和row(行)兩個屬性
        let rowNum = indexPath.row
        
        // 創建一個字符串,作為單元格的復用標識符,不同的樣式用不同的標識符
        let identifier = weeks[rowNum]
        
        // 單元格的標識符,可以看作是一種復用機制。此方法可以從所有已經開辟內存的單元格里面,選擇一個具有同樣標識符的、空閑的單元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        // 如果在可復用的單元格隊列中,沒有可復用的單元格,則創建新的單元格。新的單元格具有系統默認樣式,并擁有一個復用標識符
        if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: identifier)
            
        }
        
        cell?.textLabel?.text = weeks[rowNum]
        
        cell?.detailTextLabel?.text = "Detail infomation here"
        
        if weeks[rowNum] == "Tuesday" {
            
            cell?.imageView?.image = UIImage(named: "icon-1024")
            cell?.backgroundColor = UIColor.blue
            cell?.textLabel?.textColor = UIColor.white

        }
        return cell!
    }
    
    // 代理方法,用來響應單元格的點擊事件
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // 獲取表格中被點擊的單元格
        let cell = tableView.cellForRow(at: indexPath)
        if cell?.accessoryType == UITableViewCellAccessoryType.none {
            cell?.accessoryType = UITableViewCellAccessoryType.checkmark
        } else {
            cell?.accessoryType = UITableViewCellAccessoryType.none
        }
    }
    
    // 代理方法,用來設置單元格的編輯模式
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {
        if indexPath.row == 0 {
            return UITableViewCellEditingStyle.insert
        } else {
            return UITableViewCellEditingStyle.delete
        }
    }
    
    // 代理方法,用來響應單元格的commit事件
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        let rowNum = indexPath.row
        if editingStyle == UITableViewCellEditingStyle.delete {
            // 數組中清除數據,以保證數據的一致性
            weeks.remove(at: rowNum)
            // 表格視圖中刪除該行
            tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        } else if editingStyle == UITableViewCellEditingStyle.insert {
            weeks.insert("\(id) new day", at: rowNum)
            id += 1
            
            tableView.insertRows(at: [indexPath], with: UITableViewRowAnimation.automatic)
        }
    }
    
    // 代理方法,用來設置單元格是否允許拖動換行
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return indexPath.row != 0
//        return true
    }
    
    // 代理方法,用來響應單元格的移動事件
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let fromRow = sourceIndexPath.row
        let toRow = destinationIndexPath.row
        let day = weeks[fromRow]
        
        weeks.remove(at: fromRow)
        weeks.insert(day, at: toRow)
    }
    
    // 滾動到表格頂部
    @objc func scrollToTop(_: AnyObject) {
        let indexPath = IndexPath(row: 0, section: 0)
        tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.top, animated: true)
    }
    
    // 切換表格的編輯狀態
    @objc func switchEdit(_ button: UIButton) {
        let isEditing = tableView.isEditing
        button.setTitle(isEditing ? "edit" : "done", for: UIControlState())
        tableView.setEditing(!tableView.isEditing, animated: true)
    }
    
    var id = 0
    
    var weeks = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    
    let topButton = UIButton(type: UIButtonType.system)
    let editButton = UIButton(type: UIButtonType.system)
    
    
    // 初始化一個表格視圖
    let tableView = UITableView(frame: CGRect(x: 0, y: 40, width: 320, height: 420))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.gray
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        
        topButton.frame = CGRect(x: 100, y: 480, width: 100, height: 30)
        topButton.setTitle("scroll to top", for: UIControlState())
        topButton.addTarget(self, action: #selector(ViewController.scrollToTop(_:)), for: UIControlEvents.touchUpInside)
        
        self.view.addSubview(topButton)
        
        editButton.frame = CGRect(x: 220, y: 480, width: 50, height: 30)
        editButton.setTitle("edit", for: UIControlState.normal)
        editButton.addTarget(self, action: #selector(ViewController.switchEdit(_:)), for: UIControlEvents.touchUpInside)
        
        self.view.addSubview(editButton)
        
        self.view.addSubview(tableView)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}



另外發現個惱人的BUG,動態添加的cell在刪除的時候會出現刪除動畫渲染問題

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容