Pascal
Pascal

Reputation: 2700

viewDidLayoutSubviews for Custom UITableViewCell

I want to animate a subview of a custom TableViewCell. To perform this animation, the cell needs the width of this subview, which is laid out by an auto-layout-constraint.

However, when I use the animation-function in the cellForRowAtIndex function (mycell.animate()), the width is 0, because the subviews are not laid out yet and the animation will not work.

In a regular view, I would use viewDidLayoutSubviews(), because then the view is laid out, I can get the width and perform the animation. However, what's the equivalent function for a custom UITableViewCell?

I tried the willDisplay delegate function of the TableView, but when I print out the width of the cells subview, it still says 0...

Upvotes: 11

Views: 12242

Answers (2)

abh
abh

Reputation: 1249

It will work if you animate your view inside draw function in tableViewCell

override func draw(_ rect: CGRect) {
    super.draw(rect)

    //Your code here
}

Upvotes: 14

luk2302
luk2302

Reputation: 57183

The correct place is inside layoutSubviews:

class MyCell : UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        // do your thing
    }
}

Upvotes: 34

Related Questions