UITableView


import UIKit
// 添加兩個代理協(xié)議:表格視圖代理協(xié)議 UITableViewDelegate穿肄;表格視圖數(shù)據(jù)源協(xié)議 UITableViewDataSource
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // 代理方法辐怕,用來設(shè)置表格視圖,返回單元格行數(shù)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return weeks.count
    }
    
    // 代理方法,用來設(shè)置表格行的高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    // 代理方法嗤朴,用來初始化或復用表格視圖中的單元格
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        // 索引路徑用來標識單元格在表格中的位置剥懒。它有section(段落)和row(行)兩個屬性
        let rowNum = indexPath.row
        
        // 創(chuàng)建一個字符串,作為單元格的復用標識符匿乃,不同的樣式用不同的標識符
        let identifier = weeks[rowNum]
        
        // 單元格的標識符桩皿,可以看作是一種復用機制。此方法可以從所有已經(jīng)開辟內(nèi)存的單元格里面幢炸,選擇一個具有同樣標識符的泄隔、空閑的單元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        
        // 如果在可復用的單元格隊列中,沒有可復用的單元格宛徊,則創(chuàng)建新的單元格佛嬉。新的單元格具有系統(tǒng)默認樣式,并擁有一個復用標識符
        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
        }
    }
    
    // 代理方法暖呕,用來設(shè)置單元格的編輯模式
    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 {
            // 數(shù)組中清除數(shù)據(jù)苞氮,以保證數(shù)據(jù)的一致性
            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)
        }
    }
    
    // 代理方法湾揽,用來設(shè)置單元格是否允許拖動換行
    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)
    }
    
    // 切換表格的編輯狀態(tài)
    @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()
    }

}



另外發(fā)現(xiàn)個惱人的BUG笼吟,動態(tài)添加的cell在刪除的時候會出現(xiàn)刪除動畫渲染問題

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末库物,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子赞厕,更是在濱河造成了極大的恐慌艳狐,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件皿桑,死亡現(xiàn)場離奇詭異毫目,居然都是意外死亡,警方通過查閱死者的電腦和手機诲侮,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門镀虐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人沟绪,你說我怎么就攤上這事刮便。” “怎么了绽慈?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵恨旱,是天一觀的道長辈毯。 經(jīng)常有香客問我,道長搜贤,這世上最難降的妖魔是什么谆沃? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮仪芒,結(jié)果婚禮上唁影,老公的妹妹穿的比我還像新娘。我一直安慰自己掂名,他們只是感情好据沈,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著饺蔑,像睡著了一般锌介。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上膀钠,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天掏湾,我揣著相機與錄音,去河邊找鬼肿嘲。 笑死,一個胖子當著我的面吹牛筑公,可吹牛的內(nèi)容都是我干的雳窟。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼匣屡,長吁一口氣:“原來是場噩夢啊……” “哼封救!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起捣作,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤誉结,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后券躁,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體惩坑,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年也拜,在試婚紗的時候發(fā)現(xiàn)自己被綠了以舒。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡慢哈,死狀恐怖蔓钟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情卵贱,我是刑警寧澤滥沫,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布侣集,位于F島的核電站,受9級特大地震影響兰绣,放射性物質(zhì)發(fā)生泄漏世分。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一狭魂、第九天 我趴在偏房一處隱蔽的房頂上張望罚攀。 院中可真熱鬧,春花似錦雌澄、人聲如沸斋泄。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽炫掐。三九已至,卻和暖如春睬涧,著一層夾襖步出監(jiān)牢的瞬間募胃,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工畦浓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留痹束,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓讶请,卻偏偏與公主長得像祷嘶,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子夺溢,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容