swift UITableView

UITableView是我们开发过程中比较常用的,用于显示一系列对象,UITableView继承自UIScrollView,UIScrollView可以在任意方向滑动,而UITableView只在垂直方向上滑动。UITableView中的内容是由UITableViewCell负责显示的。

UITableView的内容有UITableViewCell来显示。创建UITableViewCell的时候,可以自定义Cell也可以使用系统自带的样式,系统的样式有4种

.value1 包含一个左侧的可选视图和一个左对齐的标签对象,在单元格右侧还有一个灰色、右对齐的标签对象。
截屏2021-01-25 上午11.21.04.png
.value2 包含一个左侧、右对齐的蓝色文字标签对象和一个右侧的左对齐的标签对象。
截屏2021-01-25 上午11.21.40.png
.default 包含一个左侧的可选图像视图,和一个左对齐的标签对象。
截屏2021-01-25 上午11.23.05.png
.subtitle 包含一个左侧的可选图像视图,和一个左对齐的标签对象,在这个标签对象下方,还有一个字体较小的标签对象。
截屏2021-01-25 上午11.23.30.png

创建一个UITableView

设置代理
UIViewController,UITableViewDataSource,UITableViewDelegate
var listTableView = UITableView()
//        初始化UITableView style有两种 plain 和grouped,在Cell不能填满屏幕的情况下选用grouped,不会再空白处出现分割线
        
        listTableView = UITableView(frame: view.bounds, style: .grouped)
        view.addSubview(listTableView)
        listTableView.mas_makeConstraints { (make) in
            make?.left.mas_equalTo()(0)
            make?.top.equalTo()(view.mas_top)?.offset()(CGFloat(topSafeAreaHeight))
            make?.width.mas_equalTo()(kScreenWidth)
            make?.bottom.mas_equalTo()(-bottomSafeAreaHeight)
        }
//        设置代理
        listTableView.delegate = self
        listTableView.dataSource = self
        listTableView.backgroundColor = .white


实现tableView的代理方法
    //MARK: 章节的个数
        func numberOfSections(in tableView: UITableView) -> Int {
            return 6
        }
    //MARK: 每一个章节的标题
        func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
            return keys[section]
        }
        //MARK: 设置索引序列内容
        func sectionIndexTitles(for tableView: UITableView) -> [String]? {

            return keys
        }
    // cell的行数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
//    列表的内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
 
               var cell = tableView.dequeueReusableCell(withIdentifier: cellid)
               if cell==nil {
                   cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellid)
               }
        
               cell?.textLabel?.text = "标题"
               cell?.detailTextLabel?.text = "内容"
               cell?.imageView?.image = UIImage(named:"bfship")
        
        return cell!
    }
    // 设置cell高度
       func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
           return 70.0
       }
       // 选中cell后执行此方法
       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
           print(indexPath.row)
     
       }

自定义cell

创建UITableViewCell
截屏2021-01-25 下午2.45.41.png
截屏2021-01-25 下午2.45.36.png
var userLabel:UILabel!      // 名字
        var birthdayLabel:UILabel!  // 出生日期
        var sexLabel:UILabel!       // 性别
//添加实例化方法
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
        // 名字
                userLabel = UILabel(frame: CGRect(x: 74, y: 18, width: 70, height: 15))
                userLabel.textColor = UIColor.black
                userLabel.font = UIFont.boldSystemFont(ofSize: 15)
                userLabel.textAlignment = .left
                
                // 性别
                sexLabel = UILabel(frame: CGRect(x: 150, y: 20, width: 50, height: 13))
                sexLabel.textColor = UIColor.black
                sexLabel.font = UIFont.systemFont(ofSize: 13)
                sexLabel.textAlignment = .left
                
                // 出生日期
                birthdayLabel = UILabel(frame: CGRect(x: 74, y: 49, width: width-94, height: 13))
                birthdayLabel.textColor = UIColor.gray
                birthdayLabel.font = UIFont.systemFont(ofSize: 13)
                birthdayLabel.textAlignment = .left
                
                
                contentView.addSubview(userLabel)
                contentView.addSubview(sexLabel)
                contentView.addSubview(birthdayLabel)
    
    }

然后在swift文件里面调用

var dataSource = [[String:String]()]//定义数据容器

dataSource = [["type":"no","name":"张三","sex":"男","icon":"my_def_photo","birthday":"2017-10-11"],
                      ["type":"no","name":"李四","sex":"男","icon":"my_def_photo","birthday":"2011-12-30"],
                      ["type":"no","name":"王五","sex":"女","icon":"my_def_photo","birthday":"2014-9-10"],
                      ["type":"no","name":"JIM","sex":"赵六","icon":"my_def_photo","birthday":"2008-10-1"]]
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
修改代理方法,给cell赋值
//    列表的内容
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
        var cell:DemoTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? DemoTableViewCell
                if cell==nil {
                    cell = DemoTableViewCell(style: .subtitle, reuseIdentifier: cellid)
                }

        let dict:Dictionary = dataSource[indexPath.row]

         cell?.userLabel.text = dict["name"]
         cell?.sexLabel.text = dict["sex"]
         cell?.birthdayLabel.text = dict["birthday"]
  
        return cell!
    }

cell的选择和取消选择

首先定义了一个数据源,因为是单选,所以用的是数组嵌套字典,key就是支付方式,value是代表是否选中个状态的string,如果选中,就把数据源里这个位置的value变成select,但是只能单选,所以还需要把其他的都变成no。

cell的实例化和复用代理方法中,可以看到,如果数据源里的value是selecrt,就把 accessoryType属性设置成checkmark。

tableView(_:, didSelectRowAt:)方法中,可以看到,用For循环来修改元数据中选中状态的value,然后调用reloadData()方法刷新cell。

cell的accessoryType属性的值是枚举UITableViewCellAccessoryType:

有以下5种样式

none 没有任何的样式
detailButton 右侧蓝色的圆圈,中间带叹号
detailDisclosureButton 右侧蓝色圆圈带叹号,它的右侧还有一个灰色向右的箭头
disclosureIndicator 右侧一个灰色的向右箭头
checkmark 右侧蓝色对号
cell = DemoTableViewCell(style: .subtitle//设置style
                                             , reuseIdentifier: cellid)

用数据源中 的type来判断是否选择

 // 选中cell后执行此方法
       func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
           print(indexPath.row)
        var i = 0
            for var dict in dataSource {
                if i == indexPath.row {
                    dict.updateValue("select", forKey: "type")
                    dataSource[i] = dict
                } else {
                    dict.updateValue("no", forKey: "type")
                    dataSource[i] = dict
                }
                i = i+1
            }

            tableView.reloadData()
       }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
        var cell:DemoTableViewCell? = tableView.dequeueReusableCell(withIdentifier: cellid) as? DemoTableViewCell
                if cell==nil {
                    cell = DemoTableViewCell(style: .subtitle, reuseIdentifier: cellid)
                }

        let dict:Dictionary = dataSource[indexPath.row]

         cell?.userLabel.text = dict["name"]
         cell?.sexLabel.text = dict["sex"]
         cell?.birthdayLabel.text = dict["birthday"]

        let type = dict["type"]
//判断当前的状态
        if type == "select" {
            cell?.accessoryType = .checkmark
        } else {
   // 如果是多选的话注释else中的内容
            cell?.accessoryType = .none
        }
        return cell!
    }

cell的插入和删除

插入和删除设计到的两个代理方法:

tableView(_ tableView:, editingStyleForRowAt indexPath:)
确定编辑模式,Add or Delete
tableView(_ tableView:, commit editingStyle:, forRowAt indexPath:)
当执行编辑操作时,调用此方法
和一个开启TableView编辑模式的方法:

setEditing(_ editing:, animated:)
editing: 是否开启编辑状态
animated: 是否有动画效果

//在右上方添加一个编辑按钮
var clickCutton = UIButton()
 view.addSubview(clickCutton)
        clickCutton.mas_makeConstraints { (make) in
            make?.right.equalTo()(view.mas_right)?.offset()(-15)
            make?.top.equalTo()(view.mas_top)?.offset()(35)
            make?.width.mas_equalTo()(100)
            make?.height.mas_equalTo()(30)
        }
        clickCutton.backgroundColor = .white
        clickCutton.setTitle("编辑", for: .normal)
        clickCutton.setTitleColor(.black, for: .normal)
        clickCutton.addTarget(self, action: #selector(clickCuttonAction), for: .touchUpInside)
//    点击打开关闭编辑模式
    @objc func clickCuttonAction() {
        listTableView.setEditing(!listTableView.isEditing, animated: true)
        }

//    insert: 添加操作
//    delete: 删除操作
//    none: 没有任何操作
    //MARK: 编辑模式,增加还是删除
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {

//                return .delete

            return .insert
        }
//MARK: 执行编辑操作时,调用此方法
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        
        if editingStyle == .insert {
            //添加
            dataSource.insert(["type":"no","name":"小明","sex":"男","icon":"my_def_photo","birthday":"2017-10-11"], at: indexPath.row)
            
            tableView.insertRows(at: [indexPath], with: .right)

            } else {
//                    删除
                dataSource.remove(at: indexPath.row)
                            
                 tableView.deleteRows(at: [indexPath], with: .left)

            }
    }
//MARK: 修改删除时的文字
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String?{
           return "删除"
    }

cell位置移动功能

·允许用户拖动位于单元格右侧的排序图标,来重新排序TableView中的单元格。类似于支付宝在选择支付顺序时候的效果

·设置cell是否可移动

·tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath)

·每次移动结束后会调用此方法

tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath)

移动功能同样需要开启编辑模式setEditing(_: ,animated:)

//编辑模式选择.none
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
            return .none
        }
//MARK: 设置cell是否可移动
        func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
            return true
        }
        //MARK: 移动结束后调用此方法
        func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
            
            let data = dataSource[sourceIndexPath.row]
            dataSource.remove(at: sourceIndexPath.row)
            dataSource.insert(data, at: destinationIndexPath.row)
        }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,444评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,867评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,157评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,312评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,673评论 3 289
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,802评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,010评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,743评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,470评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,696评论 2 250
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,187评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,538评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,188评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,127评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,902评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,889评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,741评论 2 274

推荐阅读更多精彩内容