检测UITableViewCell何时加载

时间:2016-02-22 16:55:23

标签: ios swift uitableview

我需要能够检测到我的自定义UITableViewCell何时被加载到屏幕上,以便我可以以编程方式对其中的视图执行操作。我可以使用的唯一代码是在自定义layoutSubviews()中实现UITableViewCell,但这是不好的做法,因为layoutSubviews()被多次调用。另外,将我的代码放在awakeFromNib()中并不起作用,因为我需要调用一个委托属性,该属性在此时尚未设置。我怎样才能做到这一点?

3 个答案:

答案 0 :(得分:9)

有两种不同的方法可以做到。

UITableViewDelegate中,您可以实现在即将显示单元格时调用的委托方法。

func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    // Update the cell
}

或者在UITableViewCell子类中,您可以实现didMoveToSuperView

override func didMoveToSuperview() {
    super.didMoveToSuperview()
    if superview != nil {
        // Update the cell
    }
}

答案 1 :(得分:0)

恕我直言tableView:cellForRowAtIndexPath:中最明显的地方,就是在将实例队列化并在那里完成相关的初始化之后,只需添加对自定义单元格的自定义方法的调用。

答案 2 :(得分:0)

您可以轻松使用以下功能跟踪tableViewCell: -

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// return n ( n = number of rows required )
// If n > 0, the function below will get called n times
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Identifier", forIndexPath: indexPath) as UITableViewCell!
//Create views, labels, buttons whatever you want and wherever you want.
//Add them to the cell by using cell.addSubview("Your view/label")
return cell
}
相关问题