美文网首页Swift学习swiftSwift
Swift_tableView_cell中子视图的获取方式

Swift_tableView_cell中子视图的获取方式

作者: ChinaSwift | 来源:发表于2016-01-07 17:02 被阅读1272次

1.笨蛋型获取

eg:在一个for循环里面,获取子视图label
for cell in tableView.visibleCells{
    let label = cell.subViews.first?.subViews.first as! UILabel
        if label.text!.isEmpty{
           ...
        }
}

2.上进型获取

eg:在一个for循环里面,获取子视图label
for cell in tableView.visibleCells{
    let label = cell.contentView.subViews[0] as! UILabel
        if label.text!.isEmpty{
                ...
        }
}

3.高效型获取

前提是给子视图指定一个tag数。
eg:在一个for循环里面,获取子视图uitextfield
for cell in tableView.visibleCells{
   if let label = cell.viewWithTag(2) {
        let lab = label as! UITextField
        print(lab.text)
           ...
        }
}

4.局限型获取

前提是cell类为原始的类,而且cell的style为非custom
cell.textLabel?.text = "Grandre"
cell.detailTextLabel?.text = "ChinaSwift"
//获取cell的imageView,
cell.imageView?.image = UIImage(named: "Grandre")
cell.imageView?.layer.cornerRadius = 22
cell.imageView?.layer.masksToBounds = true

当然,如果自定义类的时候,cell里面拖进自己想要子视图或控件,再跟自定义类代码绑定。这样就更容易获取并控制了。

小弟拙见,欢迎指正补充,万分感谢。

相关文章

网友评论

  • Code_Ninja:为什么要这么获取?需求是什么?
    ChinaSwift:@Code_Ninja 是指tableView.cellForRowAtIndexPath(<#T##indexPath: NSIndexPath##NSIndexPath#>)吗? 我举例是一个for 循环里面,即是要同时操作多个row哦。cellforrow,row要多个值的时候,还是要追溯到循环里面吧?
    Code_Ninja:@Code_Ninja 明白,好奇为什么要这样操作visiblecells,完全可以在cellforrow里面单独操作一个cell,这样效率会高一点
    ChinaSwift:@Code_Ninja 给子视图赋值的时候。或是检验cell中元素的时候。

本文标题:Swift_tableView_cell中子视图的获取方式

本文链接:https://www.haomeiwen.com/subject/uzyfkttx.html