zorro2b
zorro2b

Reputation: 2257

How to avoid infinite layoutSubviews

I have a UITableViewCell subclass which overrides layoutSubviews to apply a fade effect to a webview. For the most part it works fine, but sometimes it ends up in a state where layoutSubvies is called constantly with alternating values for the content height for the webview.

Is there some other place I could apply this gradient to avoid this issue?

CAGradientLayer* gradientLayer = nil;
int webViewHeight = 0;

- (void)layoutSubviews
{
    NSLog(@"layoutSubviews %f", self.webView.scrollView.contentSize.height);

    [super layoutSubviews];

    if (self.webView.scrollView.contentSize.height == webViewHeight) {
        // nothing has changed
        return;
    }

    if (gradientLayer != nil) {
        [gradientLayer removeFromSuperlayer];
        gradientLayer = nil;
    }

    // if cell height is less than web view height we must fade
    if (self.frame.size.height < self.webView.scrollView.contentSize.height) {
        webViewHeight = self.webView.scrollView.contentSize.height;
        gradientLayer = [CAGradientLayer layer];

        NSObject* fadeColor = (NSObject*)[UIColor colorWithWhite:1.0 alpha:.9].CGColor;
        NSObject* transparentColor = (NSObject*)[UIColor colorWithWhite:1.0 alpha:0.0].CGColor;

        gradientLayer.colors = [NSArray arrayWithObjects:transparentColor, fadeColor, nil];
        gradientLayer.locations = [NSArray arrayWithObjects:
                               [NSNumber numberWithFloat:0.5],
                               [NSNumber numberWithFloat:1.0], nil];

        gradientLayer.bounds = self.bounds;
        gradientLayer.anchorPoint = CGPointZero;

        [self.layer addSublayer:gradientLayer];
    }
}

Upvotes: 0

Views: 1442

Answers (1)

ingconti
ingconti

Reputation: 11636

my TWO cents for similar issue. Hope can help others. After debugging a little, I noted ALSO adding CALayer will re-invoke layoutSubviews

So if You call:

    self.layer.addSublayer(anotherLayer)

you wil be re-called in layoutSubviews.

Upvotes: 0

Related Questions