Detect when UITableViewCell did load

末鹿安然 提交于 2020-07-06 08:44:11

问题


I need to be able to detect when my custom UITableViewCell has been loaded on screen, so that I can programmatically do stuff to the view inside it. The only code I could get working was implementing layoutSubviews() inside the custom UITableViewCell, but this is bad practice because layoutSubviews() is called more than one time. Also, putting my code in awakeFromNib() doesn't work because I need to call a delegate property, which hasn't been set at that point. How can I achieve this?


回答1:


There are two different ways you could do it.

In your UITableViewDelegate you can implement the delegate method that is called when a cell is about to be displayed.

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

Or in your UITableViewCell subclass you could implement didMoveToSuperView.

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



回答2:


The most obvious place IMHO would be in tableView:cellForRowAtIndexPath:, just after having dequeued an instance and done the relevant init there, just add a call to a custom method of your custom cell.




回答3:


You can easily use the functions below to track the 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
}


来源:https://stackoverflow.com/questions/35559352/detect-when-uitableviewcell-did-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!