gpt4 book ai didi

ios - 我可以设置 `attributedText` 的 `UILabel` 属性吗

转载 作者:IT老高 更新时间:2023-10-28 11:37:52 24 4
gpt4 key购买 nike

我可以设置 attributedText UILabel 的属性(property)目的?我尝试了以下代码:

UILabel *label = [[UILabel alloc] init];
label.attributedText = @"asdf";

但它给出了这个错误:

Property "attributedText" not found on object of type 'UILabel *'

#import <CoreText/CoreText.h>不工作

最佳答案

以下是如何在标签上使用属性文本的完整示例:

NSString *redText = @"red text";
NSString *greenText = @"green text";
NSString *purpleBoldText = @"purple bold text";

NSString *text = [NSString stringWithFormat:@"Here are %@, %@ and %@",
redText,
greenText,
purpleBoldText];

// If attributed text is supported (iOS6+)
if ([self.label respondsToSelector:@selector(setAttributedText:)]) {

// Define general attributes for the entire text
NSDictionary *attribs = @{
NSForegroundColorAttributeName: self.label.textColor,
NSFontAttributeName: self.label.font
};
NSMutableAttributedString *attributedText =
[[NSMutableAttributedString alloc] initWithString:text
attributes:attribs];

// Red text attributes
UIColor *redColor = [UIColor redColor];
NSRange redTextRange = [text rangeOfString:redText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:@{NSForegroundColorAttributeName:redColor}
range:redTextRange];

// Green text attributes
UIColor *greenColor = [UIColor greenColor];
NSRange greenTextRange = [text rangeOfString:greenText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:@{NSForegroundColorAttributeName:greenColor}
range:greenTextRange];

// Purple and bold text attributes
UIColor *purpleColor = [UIColor purpleColor];
UIFont *boldFont = [UIFont boldSystemFontOfSize:self.label.font.pointSize];
NSRange purpleBoldTextRange = [text rangeOfString:purpleBoldText];// * Notice that usage of rangeOfString in this case may cause some bugs - I use it here only for demonstration
[attributedText setAttributes:@{NSForegroundColorAttributeName:purpleColor,
NSFontAttributeName:boldFont}
range:purpleBoldTextRange];

self.label.attributedText = attributedText;
}
// If attributed text is NOT supported (iOS5-)
else {
self.label.text = text;
}

关于ios - 我可以设置 `attributedText` 的 `UILabel` 属性吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11031623/

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