Reputation: 8376
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?
Upvotes: 10
Views: 15624
Reputation: 327
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
}
Upvotes: -1
Reputation: 17710
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.
Upvotes: 0
Reputation: 13276
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
}
}
Upvotes: 22