viewDidLayoutSubviews for Custom UITableViewCell
Asked Answered
T

2

11

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...

Theiss answered 24/10, 2017 at 8:25 Comment(5)
You probably have to create a subclass of UITableViewCell and then go from there.Scull
hmm I actually have, sorry if that's been unclearTheiss
I know this is probably deeper than that but, have you tried assigning the width to the table cell in cellForRow:at:? cell.frame.size.width = tableView.frame.size.widthBlowbyblow
layoutSubviews inside the cell subclass might do the trick.Scull
lol thanks @lu2302, it really works! Didn't think it can be that easy :)Theiss
S
34

The correct place is inside layoutSubviews:

class MyCell : UITableViewCell {
    override func layoutSubviews() {
        super.layoutSubviews()
        // do your thing
    }
}
Scull answered 24/10, 2017 at 16:42 Comment(5)
Hi, I'm trying to use this approach while adding a gradient to a custom UITableViewCell. I call my applyGradient() function inside of layoutSubviews() My problem is that when the table loads, I see no gradient, but after I click the cell, the gradient will show. Any idea of why the gradient won't show before clicking? I've tried calling layoutSubviews() from different places in my code with no luck. @ScullIlluviation
@Illuviation i've had your issue and the code above did it without the need to call the function, just put the gradient code within the function above in tableViewCell class :)Amateurism
I've had a similar problem while setting shadow for a subview. Apparently, the layoutSubviews method doesn't get called after the view has been laid out by autolayout. (or it is returning 0 for some reason)Corri
layoutSubviews() did not work in my case. After reuse of the cell, gradient frame was wrong, even though i removed gradient and apply it again in reuse. Updating frame inside draw(_ rect: CGRect) solved my problemLadylove
dropping shadow also worked only from draw(_ rect: CGRect)Binni
C
14

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

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

    //Your code here
}
Curly answered 28/2, 2019 at 15:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.