浏览了几个NSAttributedString
示例,但似乎无法使其正常工作。我正在尝试更改NSMutableAttributedString
部分的大小和颜色。
我尝试了一些变体:
NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];
//Black and large
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor blackColor]} range:NSMakeRange(0, 11)];
//Rest of text -- just futura
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(12, ((hintText.length -1) - 12))];
这只会改变文本的大小,而不是颜色。有人能指出我正确的方向吗?
编辑:我这样使用它:myUILabel.attributedText = hintText
;
答案 0 :(得分:3)
当我尝试做这样的事情时,我发现构建单个部件(每个部件都是NSAttributedString
)更容易,然后将它们“粘合”在一起,如下所示:< / p>
NSAttributedString *string1 = // Get the red and large string here
NSAttributedString *string2 = // Get the just futura string here
NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] init];
[hintText appendAttributedString:string1];
[hintText appendAttributedString:string2];
我发现这样可以更容易地遵循逻辑流程,而且我从未发现这种方式存在需要优化的性能限制。
<小时/> 的 更新 强>
FWIW,我得到以下代码,因为我相信OP的愿望:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableAttributedString *hintText = [[NSMutableAttributedString alloc] initWithString:@"This is red and huge and this is not"];
//Red and large
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:20.0f], NSForegroundColorAttributeName:[UIColor redColor]} range:NSMakeRange(0, 20)];
//Rest of text -- just futura
[hintText setAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"Futura-Medium" size:16.0f]} range:NSMakeRange(20, hintText.length - 20)];
[self.button setAttributedTitle:hintText forState:UIControlStateNormal];
}
请注意,他正在指定[UIColor blackColor]
,我将其更新为[UIColor redColor]
。此外,我更新了范围计算,以包括“这是红色和巨大”中的所有字符。