Swift - UITableView

創(chuàng)建UITablView

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    
    var Names = ["A","B","C","D","E","F"]
    var tableView:UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //創(chuàng)建表格圖
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //將代理,數(shù)據(jù)來源設(shè)為自己
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //創(chuàng)建表頭標(biāo)簽
        let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 30))
        headerLabel.text = "Header"
        self.tableView?.tableHeaderView = headerLabel
        
        self.view.addSubview(tableView)
    }
    //設(shè)置分區(qū)數(shù)(不設(shè)置默認(rèn)為1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    //設(shè)置單元格數(shù)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Names.count
    }
    //設(shè)置單元格內(nèi)容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //設(shè)置重用單元格名稱
        let identifier = "reusedCell"
        //使用重用單元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identify)
        //如果單元格為nil創(chuàng)建重用單元格
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: identify)
        }
        cell?.textLabel?.text = Names[indexPath.row]
        return cell!
    }
    //自定義單元格高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    //點(diǎn)擊單元格響應(yīng)時(shí)間
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被點(diǎn)擊的單元格的顏色立即恢復(fù)
        let cell = tableView.cellForRow(at: indexPath)
        if cell?.accessoryType == UITableViewCell.AccessoryType.none{
            cell?.accessoryType = .checkmark
            print("你選擇了:\(String(describing: cell?.textLabel?.text))")
        }else{
            cell?.accessoryType = .none
        }
    }
    
}

使用不同樣式單元格

import UIKit

class CustomizeTableViewCell: UITableViewCell {
    var UserImage:UIImageView!
    var UserName:UILabel!
    var Detail:UIButton!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.UserImage = UIImageView(image: UIImage(named: "UserImage"))
        self.UserImage.center = CGPoint(x: 30, y: 22)
        
        self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))
        self.UserName.text = "自定義單元格"
        
        self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))
        self.Detail.setTitle("詳情", for: .normal)
        self.Detail.backgroundColor = UIColor.gray
        self.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)
        
        self.addSubview(self.UserName)
        self.addSubview(self.UserImage)
        self.addSubview(self.Detail)
    }
    @objc func showDetail(){
        print("顯示詳情信息")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

效果圖:
屏幕快照 2019-01-10 下午1.54.49.png

自定義UItableViewCell

創(chuàng)建一個(gè)Cocoa Touch class文件,設(shè)置父類:UITableViewCell,名稱為CustomizeTableViewCell

編輯CustomizeTableViewCell:

import UIKit

class CustomizeTableViewCell: UITableViewCell {
    var UserImage:UIImageView!
    var UserName:UILabel!
    var Detail:UIButton!
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.UserImage = UIImageView(image: UIImage(named: "UserImage"))
        self.UserImage.center = CGPoint(x: 30, y: 22)
        
        self.UserName = UILabel(frame: CGRect(x: 80, y: 0, width: 120, height: 40))
        self.UserName.text = "自定義單元格"
        
        self.Detail = UIButton(frame: CGRect(x: 240, y: 8, width: 60, height: 24))
        self.Detail.setTitle("詳情", for: .normal)
        self.Detail.backgroundColor = UIColor.gray
        self.Detail.addTarget(self, action: #selector(showDetail), for: .touchUpInside)
        
        self.addSubview(self.UserName)
        self.addSubview(self.UserImage)
        self.addSubview(self.Detail)
    }
    @objc func showDetail(){
        print("顯示詳情信息")
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

編輯ViewController:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var user = ["A","B","C"]
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: self.view.frame)
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return user.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell:CustomizeTableViewCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? CustomizeTableViewCell
        if cell == nil{
            cell = CustomizeTableViewCell(style: .default, reuseIdentifier: identifier)
        }
        cell?.UserName.text = user[indexPath.row]
        return cell!
    }

}

給文章添加章節(jié)和索引

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    
    var Section = ["A","B","C","D","E","F","G","H","I","G","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","z"]
    var Content =   [["1","2","3"],["3","4"],["5","6"],["7","8"],["9","10"],["11","12"],["13","14"],["15","16"],["12","21"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"],["1","1"]]
    var tableView:UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //創(chuàng)建表格圖
        self.tableView = UITableView(frame: self.view.frame, style: .grouped)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //創(chuàng)建表頭標(biāo)簽
        let headerLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2, y: 0, width: self.view.bounds.width, height: 30))
        headerLabel.text = "添加章節(jié)和索引"
        self.tableView?.tableHeaderView = headerLabel
        self.view.addSubview(tableView)
        print(Content.count)
    }
    //設(shè)置分區(qū)數(shù)(不設(shè)置默認(rèn)為1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return Section.count
    }
    //設(shè)置單元格數(shù)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Content[section].count
    }
    //設(shè)置單元格表頭
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.Section[section]
    }
    //設(shè)置單元格表尾
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        return "有\(zhòng)(self.Content[section].count)個(gè)控件"
    }
    //設(shè)置索引內(nèi)容
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.Section
    }
    //設(shè)置單元格內(nèi)容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identify)
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: identify)
        }
        let section = indexPath.section
        var data = self.Content[section]
        cell?.textLabel?.text = data[indexPath.row]
        return cell!
    }
    //點(diǎn)擊單元格響應(yīng)時(shí)間
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被點(diǎn)擊的單元格的顏色立即恢復(fù)
        let section = indexPath.section
        var data = self.Content[section]
        let alertController = UIAlertController(title: "提示", message: "你點(diǎn)擊了:\(data[indexPath.row])", preferredStyle: .alert)
        let ok = UIAlertAction(title: "確定", style: .default, handler: nil)
        alertController.addAction(ok)
        present(alertController, animated: true, completion: nil)
    }
    
}

單元格的刪除,插入,移動(dòng)

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var SectionNum = ["delete","insert","move"]
    var Content = [["A","B"],["C","D"],["E","F"]]
    var tableView:UITableView!
    override func viewDidLoad() {
     super.viewDidLoad()
        tableView = UITableView(frame: self.view.frame)
        tableView.dataSource = self
        tableView.delegate = self
        //設(shè)置是否為編輯模式
        tableView.setEditing(false, animated: true)
        self.view.addSubview(tableView)
        //添加一個(gè)手勢來開啟/關(guān)閉編輯模式
        let Tap = UITapGestureRecognizer(target: self, action: #selector(OpenEdit))
        Tap.numberOfTapsRequired = 2
        Tap.numberOfTouchesRequired = 1
        self.view.addGestureRecognizer(Tap)
        
    }
    @objc func OpenEdit(){
        if self.tableView.isEditing{
            tableView.setEditing(false, animated: true)
        }else{
            tableView.setEditing(true, animated: true)
        }
    }
    //設(shè)置區(qū)域數(shù)
    func numberOfSections(in tableView: UITableView) -> Int {
        return SectionNum.count
    }
    //設(shè)置行數(shù)
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let data = Content[section]
        return data.count
    }
    //設(shè)置內(nèi)容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: identifier)
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: identifier)
        }
        let data = Content[indexPath.section]
        cell?.textLabel?.text = data[indexPath.row]
        return cell!
    }
    //設(shè)置章節(jié)名稱
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return SectionNum[section]
    }
    //設(shè)置編輯狀態(tài)下顯示的圖標(biāo)(none,insert,delete三種圖案)
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        if indexPath.section == 0{
            return UITableViewCell.EditingStyle.delete
        }else if indexPath.section == 1{
            return UITableViewCell.EditingStyle.insert
        }
        return UITableViewCell.EditingStyle.none
    }
    //使用刪除,插入執(zhí)行此方法
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete{
            self.Content[indexPath.section].remove(at: indexPath.row) //刪除選項(xiàng),并設(shè)置刪除的效果
            //更新表格數(shù)據(jù)
            self.tableView.reloadData()
        }else {
            self.Content[indexPath.section].insert("F", at: indexPath.row)
            self.tableView.reloadData()
            
        }
    }
    //修改刪除提示的問題
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "X"
    }
    //設(shè)置單元格的位置可以拖動(dòng)
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 2{
            return true
        }
        return false
    }
    //移動(dòng)完單元格調(diào)用此方法
    func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        print("你使用了此方法")
        let formRow = sourceIndexPath.row
        let toRow = destinationIndexPath.row
        let formContent = Content[formRow]
        Content.remove(at: formRow)
        Content.insert(formContent, at: toRow)
        }
    }

效果圖:
屏幕快照 2019-01-10 下午1.30.48.png

TableViewCell嵌套

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var articles = ["A","B"]
    var Contents = ["1","2"]
    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame:self.view.frame)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        self.view.addSubview(tableView)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articles.count*2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let idA = "articlesCell"
        let idB = "ContentsCell"
        var CellA:UITableViewCell?
        var CellB:UITableViewCell?
        if indexPath.row%2 == 0{
            CellA = tableView.dequeueReusableCell(withIdentifier: idA)
            if CellA == nil{
                CellA = UITableViewCell(style: .default, reuseIdentifier: idA)
            }
            CellA?.textLabel?.text = articles[indexPath.row/2]
            return CellA!
        }else{
            CellB = tableView.dequeueReusableCell(withIdentifier: idB)
            if CellB == nil{
                CellB = UITableViewCell(style: .default, reuseIdentifier: idB)
            }
            CellB?.textLabel?.text = Contents[indexPath.row/2]
            return CellB!
        }
    }
    
    
}

嵌套自定義單元格

創(chuàng)建一個(gè)自定義swift文件,父類為UITableViewCell,名稱為CustomizeTableVIewCell
編輯CustomizeTableViewCell:

import UIKit

class CustomizeTableViewCell: UITableViewCell,UITableViewDataSource,UITableViewDelegate {
    var tableView:UITableView!
    var Content:[String] = []
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        //進(jìn)行初始化,后續(xù)在進(jìn)行更改
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
        tableView.dataSource = self
        tableView.delegate = self
        //設(shè)置是否允許滑動(dòng)(設(shè)為false,防止內(nèi)容跟著手指滑動(dòng)而滑動(dòng))
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        self.addSubview(tableView)
    }
    //設(shè)置單元格數(shù)量
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Content.count
    }
    //設(shè)置單元格內(nèi)容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let id = "reusedCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: id)
        if cell == nil{
            cell = UITableViewCell(style: .default, reuseIdentifier: id)
        }
        cell?.textLabel?.text = Content[indexPath.row]
        cell?.textLabel?.font = UIFont.systemFont(ofSize: 12)
        cell?.textLabel?.numberOfLines = 0
        return cell!
    }
    //設(shè)置單元格高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let ContentNum = Content[indexPath.row]
        //計(jì)算內(nèi)容高度(ContentSize.width/170計(jì)算有多少行文字)
        let ContentSize = ContentNum.boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)
        let cellHeight = ContentSize.height*(ContentSize.width/170)
        if cellHeight < 30{
            return 30
        }else{
            return cellHeight
        }
    }
    //根據(jù)數(shù)據(jù)源內(nèi)容來設(shè)置UITableView高度(+50防止內(nèi)容擁擠)
    func setContentForTable(_ content:[String]){
        self.Content = content
        
        var tableHeight:CGFloat = 0
        for i in 0..<content.count
        {
            let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)
        tableHeight += ContentSize.height*(ContentSize.width/170)
        }
        tableView.frame = CGRect(x: 20, y: 0, width: 300, height: tableHeight + 50)
        tableView.reloadData()
    }
    func getMyHeight()->CGFloat{
        return tableView.frame.size.height
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

編輯ViewController:

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    var articles = ["徐志摩","克萊兒?麥克福爾","東野圭吾"]
    var Contents = [["我是天空里的一片云,偶爾投影在你的波心,你不必訝異,更無須歡喜,在轉(zhuǎn)瞬間消滅了蹤影。你我相逢在黑夜的海上,你有你的,我有我的,方向,你記得也好,最好你忘掉,在這交會(huì)時(shí)互放的光亮"],["當(dāng)靈魂休眠的時(shí)候,我敢肯定它們得到了片刻的平靜和安寧。111111111111111111111111"],["你我都不可能擺脫時(shí)鐘的束縛,彼此都已淪為社會(huì)這個(gè)時(shí)鐘的齒輪,一旦少了齒輪,時(shí)鐘就會(huì)出亂子??v然自己渴望率性而為,周遭也不容許,我們雖然得到了安定,但失去自由也是不爭的事實(shí)。"]]
    override func viewDidLoad() {
        super.viewDidLoad()
        let tabView = UITableView(frame:CGRect(x: 0, y: 20, width: self.view.bounds.width, height: self.view.bounds.height))
        tabView.delegate = self
        tabView.dataSource = self
        tabView.separatorStyle = .none
        self.view.addSubview(tabView)
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return articles.count*2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let idA = "cellForArticles"
        let idB = "cellForContent"
        
        var cell1:UITableViewCell?
        var cell2:CustomizeTableViewCell?
        
        if indexPath.row%2 == 0{
            cell1 = tableView.dequeueReusableCell(withIdentifier: idA)
            if cell1 == nil{
                cell1 = UITableViewCell(style: .default, reuseIdentifier: idA)
            }
            cell1?.textLabel?.text = articles[indexPath.row/2]
            cell1?.textLabel?.textColor = UIColor.gray
            cell1?.backgroundColor = UIColor.black
            cell1?.textLabel?.font = UIFont.systemFont(ofSize: 16)
            return cell1!
        }else{
            cell2 = tableView.dequeueReusableCell(withIdentifier: idB) as? CustomizeTableViewCell
            if cell2 == nil{
                cell2 = CustomizeTableViewCell(style: .default, reuseIdentifier: idB)
            }
            let content = Contents[indexPath.row/2]
            cell2?.setContentForTable(content)
            return cell2!
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row % 2 == 0{
            return 40
        }else{
            let Content = Contents[indexPath.row/2]
            var cellHeight:CGFloat = 0
            for i in 0..<Content.count{
                let ContentSize = Content[i].boundingRect(with: CGSize(), options: NSStringDrawingOptions.usesFontLeading, attributes: nil, context: nil)
                cellHeight += ContentSize.height*(ContentSize.width/170)
            }
            return cellHeight + 50
        }
    }
}

滾動(dòng)到底部

使用scrollToRow方法滾動(dòng)到最后一行

let secon = 1 //最后一個(gè)分組的索引(0開始,如果沒有分組則為0)
let rows = 10 //最后一個(gè)分組最后一條項(xiàng)目的索引
let indexPath = IndexPath(row: rows, section: secon)
self.tableView?.scrollToRow(at: indexPath, at:.bottom, animated: true)

使用setContentOffset設(shè)置偏移量實(shí)現(xiàn)滾動(dòng):

let offset = CGPoint(x:0, y:self.tableView!.contentSize.height
                                - self.tableView!.bounds.size.height)
self.tableView!.setContentOffset(offset, animated: true)
最后編輯于
?著作權(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)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,626評(píng)論 1 32
  • AppDelegate:func application(_ application: UIApplication...
    任任任任師艷閱讀 1,731評(píng)論 0 0
  • var tableview = UITableView() // 創(chuàng)建可變數(shù)組 var datas: NSMut...
    小_蠟筆閱讀 3,418評(píng)論 0 0
  • @應(yīng)童老師早上好!回味昨天的換老公不如換自己,總覺得和阿Q的精神勝利法有一似也有一拼,[害羞]老師能再給深度剖析一...
    小寶媽_b9af閱讀 297評(píng)論 0 0
  • 當(dāng)你我共同流亡,魂魄竟到達(dá)了同一個(gè)地方。 或許我們之間的交際只有這狹小的一方。 當(dāng)重新踏上前方,兩條直線不再有相交...
    落地寒冬草閱讀 224評(píng)論 0 0

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