2013-03-10 36 views
9

我想在標籤中加下一些文字。但是,我不知道如何獲取標籤中整個文本的範圍。這是我到目前爲止:如何在iOS 6中強調文本?

NSMutableAttributedString *mat = [self.tableLabel.attributedText mutableCopy]; 
[mat addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)} range://??]; 
self.tableLabel.attributedText = mat; 

我應該爲範圍?

+0

http://stackoverflow.com/questions/2711297/underline-text-in- uilabel – 2013-03-10 22:52:37

回答

22

對於您可能需要使用範圍:

NSMakeRange (0, mat.length); 

像這樣:

NSMutableAttributedString *mat = [self.tableLabel.attributedText mutableCopy]; 
[mat addAttributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)} range:NSMakeRange (0, mat.length)]; 
self.tableLabel.attributedText = mat; 
+2

NSMakeRange()可以說更好,因爲它不依賴於C99的隱含文字,它有一些問題。 – 2013-03-10 22:54:14

+0

確實,更新答案。 – Ares 2013-03-10 22:54:54

+0

很好用! NSMakeRange如何工作? – user1420042 2013-03-10 22:54:55

0
NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete]; 

[attributedString addAttribute:NSUnderlineStyleAttributeName 
         value:@(NSUnderlineStyleSingle) 
         range:[strComplete rangeOfString:strFirst]]; 

[attributedString addAttribute:NSForegroundColorAttributeName 
         value:[UIColor redColor] 
         range:[strComplete rangeOfString:strSecond]]; 


cell.textLabel.attributedText = attributedString; 
+0

請注意,代碼只有答案是不鼓勵的。 – GhostCat 2017-09-20 10:41:17