繁体   English   中英

使用NSMutableAttributedString更改NSString的颜色和大小部分

[英]Change color and size portion of NSString with NSMutableAttributedString

浏览了一些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 ;

当我尝试做这样的事情时,我发现构建单个部分(每个部分都是NSAttributedString )更容易,然后将它们“粘合”在一起,如下所示:

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] 此外,我更新了范围计算,以包括“这是红色和巨大”中的所有字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM