gpt4 book ai didi

ios - 将 "stolen"UILabel 层添加到其他 CALayer 的子层是否安全?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:23:48 26 4
gpt4 key购买 nike

我读了thisthis但他们似乎没有解决这个问题。以及 this 的答案似乎在 NSCoding 和 friend 中离题了,所以 ...

考虑:

- (NSAttributedString *) attributedStringForText: (NSString *) text {
NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithString:text];
UIFont * bigF = [UIFont fontWithName:@"OpenSans-Extrabold" size:20.0f] ;
UIFont * smaF = [UIFont fontWithName:@"OpenSans-Extrabold" size:12.0f] ;

[attrStr addAttribute:NSFontAttributeName value:bigF range:(NSRange){0, 3}] ;
[attrStr addAttribute:NSFontAttributeName value:smaF range:(NSRange){3, 6}] ;
[attrStr addAttribute:NSFontAttributeName value:bigF range:(NSRange){6, [text length]-6}] ;

[attrStr addAttribute:NSBackgroundColorAttributeName value:[UIColor brownColor] range:(NSRange){3, 6}] ;
return attrStr ;
}

- (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 display] ; // Yup!
return label.layer ;
}

- (void) setupLayer: (CALayer *) tileLayer
text: (NSString *) text
index: (NSUInteger) index {

CGRect (^center_rect)(CGRect, CGRect) = ^CGRect (CGRect r, CGRect into) {
CGRect centered = into ;
centered.origin.x += (into.size.width - r.size.width) / 2.0f ;
centered.origin.y += (into.size.height - r.size.height) / 2.0f ;
centered.size = r.size ;
return centered ;
} ;

CALayer * layer = [self stealLayerFromUILabelForText:text inRect:tileLayer.bounds] ;
CGRect frame = center_rect(layer.bounds, tileLayer.bounds) ;

[tileLayer addSublayer:layer] ;

layer.frame = frame ;
}

这个有效:

enter image description here

但我担心我会以某种方式滥用 UILabel 和 CALayer。一方面,UIViewUILabel 和所有这些都只是在真实 CALayer 层次结构。 OTOH 我在某种程度上依赖于许多甚至没有在这里陈述的假设。

任何人都明白为什么这会在未来进一步崩溃,或者更好的是,可以证明它不会?

最佳答案

我从 2013 年开始使用这种技术,它仍然很稳定。所以是的,我认为现在这是安全的。以前我这样做时没有在 iOS 4 或 5 上调用 -display,这在针对较新的 SDK 编译时不再有效,所以感谢这个花絮。

如果您正在寻找其他选项,这里有更多信息:Add text to CALayer

关于ios - 将 "stolen"UILabel 层添加到其他 CALayer 的子层是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171790/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com