簡體   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