如何避免无限的layoutSubviews

时间:2016-11-10 05:59:04

标签: ios objective-c layout calayer subview

我有一个UITableViewCell子类,它覆盖layoutSubviews以将淡入淡出效果应用于webview。在大多数情况下它工作正常,但有时它最终处于一种状态,其中不断调用layoutSubvies,并为webview的内容高度提供交替值。

是否有其他地方可以应用此渐变来避免此问题?

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];
    }
}

0 个答案:

没有答案