2016-02-02 44 views
0

我有一個顯示爲問題的UILabel。它以編程方式成功顯示已分配給它的問題文本。但後來根據其他條件,我必須更改標籤中的文本。具體而言,如果這是一個強制性問題,我希望在字符串的末尾顯示星號(*)標記。*應爲紅色,並且其餘的文本應該是黑色的。但它只顯示問題而不是*標記。如果我嘗試打印questLabel.text,它會在最後給出帶*標記的問題。以下是我正在嘗試的代碼即使它給控制檯中新分配的值UILabel不顯示其正確的值

questText = questLabel.text; 
     questText = [questText stringByAppendingString:@"✶"]; 
NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:questText]; 
     NSMutableAttributedString *text = 
      [[NSMutableAttributedString alloc] 
      initWithAttributedString: str]; 
      int length = (int)text.length; 
      [text addAttribute:NSForegroundColorAttributeName 
         value:[UIColor redColor] 
         range:NSMakeRange(length-1, 1)]; 
      [questLabel setAttributedText: text]; 

如果我嘗試打印questLabel.attributedText的價值:

Question{ 
}✶{ 
    NSColor = "UIDeviceRGBColorSpace 1 0 0 1"; 
} 

而對於questLabel.text值:Question✶

請幫我帶這個..預先感謝..

+0

你初始化你NSMutableAttributedString與海峽這裏, 其中該海峽是從哪裏來的? – iOSEnthusiatic

+0

@iosenthusiatic:這是複製代碼時發生的錯誤。我編輯了代碼,請現在看看 – iOSManiac

回答

1

你應該改變你的代碼。

NSString *questText = questLabel.text; 
questText = [questText stringByAppendingString:@"✶"]; 

NSMutableAttributedString *text = 
[[NSMutableAttributedString alloc] initWithString:questText]; 

int length = (int)text.length; 

[text addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, length-1)]; 
[text addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(length-1, 1)]; 
[questLabel setAttributedText: text]; 
+0

感謝您的答覆。我試過這個解決方案。但它沒有幫助我。但是我得到了值在console.But標籤沒有得到更新 – iOSManiac

+0

@iOSManiac,我試過我的自我和它的工作,可能是有你的標籤problm – iOSEnthusiatic

+0

你說得對,感謝你:)。我的標籤框架是錯誤的..修正它。現在它正確地來了 – iOSManiac

0

你也可以試試這個

NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:self.questLabel.text attributes:@{NSForegroundColorAttributeName:[UIColor blackColor]}]; 

NSMutableAttributedString *starString = [[NSMutableAttributedString alloc] initWithString:@"✶" attributes:@{NSForegroundColorAttributeName:[UIColor redColor]}]; 

[string appendAttributedString:starString]; 

[self.questLabel setAttributedText:string]; 
+0

謝謝你的回覆@ Mohsin Shah – iOSManiac

相關問題