Is it safe to add a “stolen” UILabel's layer to some other CALayer's sublayer?

99封情书 提交于 2019-12-06 15:42:13
Matt Foley

I've used this technique since 2013 and it's still stable. So yes, I think this is safe for now. Previously I was doing this without calling -display on iOS 4 or 5, which no longer works when compiled against newer SDKs, so thanks for this tidbit.

There is more information here if you're looking for other options: Add text to CALayer

This technique still works in iOS 10. IMO a UIView(in this case UILabel) is simply a delegate of its backing CALayer, so it should be safe to manipulate the underlying CALayer directly. The only problem is if you don't add the label as a subview, the label would be released and the underlying layer.delegate would become nil and the text never gets a chance to be rendered.

So we need a way to force rendering before the label is released. However it is worth mentioning that [CALayer display] should NOT be called directly per Apple's documentation. So based on the same idea, consider a safe alternative [CALayer displayIfNeeded].

- (CALayer *) stealLayerFromUILabelForText: (NSString *) text inRect: (CGRect) bounds {
    UILabel * label = [[UILabel alloc] initWithFrame:bounds] ;
    label.textColor = [UIColor whiteColor] ;
    label.font = [UIFont fontWithName:@"OpenSans-Extrabold" size:20.0f] ;
    label.attributedText = [self attributedStringForText:text] ;
    [label sizeToFit] ;
    [label.layer displayIfNeeded] ;
    return label.layer ;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!