Swift - UITableView

创建UITablView

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate{
    
    var Names = ["A","B","C","D","E","F"]
    var tableView:UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //创建表格图
        self.tableView = UITableView(frame: self.view.frame, style: .plain)
        //将代理,数据来源设为自己
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //创建表头标签
        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)
    }
    //设置分区数(不设置默认为1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    //设置单元格数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Names.count
    }
    //设置单元格内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        //设置重用单元格名称
        let identifier = "reusedCell"
        //使用重用单元格
        var cell = tableView.dequeueReusableCell(withIdentifier: identify)
        //如果单元格为nil创建重用单元格
        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
    }
    //点击单元格响应时间
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复
        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")
    }
    
}

效果图:在这里插入图片描述

自定义UItableViewCell

创建一个Cocoa Touch class文件,设置父类: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!
    }

}

给文章添加章节和索引

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()
        //创建表格图
        self.tableView = UITableView(frame: self.view.frame, style: .grouped)
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        //创建表头标签
        let headerLabel = UILabel(frame: CGRect(x: self.view.bounds.width/2, y: 0, width: self.view.bounds.width, height: 30))
        headerLabel.text = "添加章节和索引"
        self.tableView?.tableHeaderView = headerLabel
        self.view.addSubview(tableView)
        print(Content.count)
    }
    //设置分区数(不设置默认为1)
    func numberOfSections(in tableView: UITableView) -> Int {
        return Section.count
    }
    //设置单元格数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Content[section].count
    }
    //设置单元格表头
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.Section[section]
    }
    //设置单元格表尾
    func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
        return "有\(self.Content[section].count)个控件"
    }
    //设置索引内容
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        return self.Section
    }
    //设置单元格内容
    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!
    }
    //点击单元格响应时间
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView?.deselectRow(at: indexPath, animated: true)//使被点击的单元格的颜色立即恢复
        let section = indexPath.section
        var data = self.Content[section]
        let alertController = UIAlertController(title: "提示", message: "你点击了:\(data[indexPath.row])", preferredStyle: .alert)
        let ok = UIAlertAction(title: "确定", style: .default, handler: nil)
        alertController.addAction(ok)
        present(alertController, animated: true, completion: nil)
    }
    
}

单元格的删除,插入,移动

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
        //设置是否为编辑模式
        tableView.setEditing(false, animated: true)
        self.view.addSubview(tableView)
        //添加一个手势来开启/关闭编辑模式
        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)
        }
    }
    //设置区域数
    func numberOfSections(in tableView: UITableView) -> Int {
        return SectionNum.count
    }
    //设置行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let data = Content[section]
        return data.count
    }
    //设置内容
    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!
    }
    //设置章节名称
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return SectionNum[section]
    }
    //设置编辑状态下显示的图标(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
    }
    //使用删除,插入执行此方法
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete{
            self.Content[indexPath.section].remove(at: indexPath.row) //删除选项,并设置删除的效果
            //更新表格数据
            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"
    }
    //设置单元格的位置可以拖动
    func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        if indexPath.section == 2{
            return true
        }
        return false
    }
    //移动完单元格调用此方法
    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)
        }
    }

效果图:在这里插入图片描述

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!
        }
    }
    
    
}
嵌套自定义单元格

创建一个自定义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)
        //进行初始化,后续在进行更改
        tableView = UITableView(frame: CGRect(x: 0, y: 0, width: 300, height: 50))
        tableView.dataSource = self
        tableView.delegate = self
        //设置是否允许滑动(设为false,防止内容跟着手指滑动而滑动)
        tableView.isScrollEnabled = false
        tableView.separatorStyle = .none
        self.addSubview(tableView)
    }
    //设置单元格数量
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return Content.count
    }
    //设置单元格内容
    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!
    }
    //设置单元格高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let ContentNum = Content[indexPath.row]
        //计算内容高度(ContentSize.width/170计算有多少行文字)
        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
        }
    }
    //根据数据源内容来设置UITableView高度(+50防止内容拥挤)
    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 = [["我是天空里的一片云,偶尔投影在你的波心,你不必讶异,更无须欢喜,在转瞬间消灭了踪影。你我相逢在黑夜的海上,你有你的,我有我的,方向,你记得也好,最好你忘掉,在这交会时互放的光亮"],["当灵魂休眠的时候,我敢肯定它们得到了片刻的平静和安宁。111111111111111111111111"],["你我都不可能摆脱时钟的束缚,彼此都已沦为社会这个时钟的齿轮,一旦少了齿轮,时钟就会出乱子。纵然自己渴望率性而为,周遭也不容许,我们虽然得到了安定,但失去自由也是不争的事实。"]]
    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
        }
    }
}
滚动到底部

使用scrollToRow方法滚动到最后一行

let secon = 1 //最后一个分组的索引(0开始,如果没有分组则为0)
let rows = 10 //最后一个分组最后一条项目的索引
let indexPath = IndexPath(row: rows, section: secon)
self.tableView?.scrollToRow(at: indexPath, at:.bottom, animated: true)

使用setContentOffset设置偏移量实现滚动:

let offset = CGPoint(x:0, y:self.tableView!.contentSize.height
                                - self.tableView!.bounds.size.height)
self.tableView!.setContentOffset(offset, animated: true)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值