2013-08-21 63 views
68

NSAttributedString對我來說實在是難以逾越。具有兩種不同字體大小的NSAttributedString的示例?

我想設置一個UILabel有不同大小的文本,我收集NSAttributedString是要走的路,但我無法得到任何關於此的文檔。

我會喜歡它,如果有人可以幫我一個具體的例子。

舉例來說,假設我想要的文字是:

(in small letters:) "Presenting The Great..." 
(in huge letters:) "HULK HOGAN!" 

有人可以告訴我該怎麼做?甚至,我可以爲自己學習的簡單而簡單的參考資料?我發誓我試圖通過文檔瞭解這一點,甚至通過堆棧溢出的其他例子,我只是沒有得到它。

回答

150

你會做這樣的事......

NSMutableAttributedString *hogan = [[NSMutableAttributedString alloc] initWithString:@"Presenting the great... Hulk Hogan!"]; 
[hogan addAttribute:NSFontAttributeName 
       value:[UIFont systemFontOfSize:20.0] 
       range:NSMakeRange(24, 11)]; 

這將設置在20點文本中的最後兩個詞;字符串的其餘部分將使用默認值(我相信這是12分)。有關設置文本大小可能會引起混淆的是,您必須同時設置字體的大小 - 每個對象封裝了這兩個屬性。

+0

查看SWIFT範圍的這個答案:http://stackoverflow.com/a/27041376/1736679 – Efren

0

如果你想這樣做的簡單方法,有一個名爲OHAttributedLabel的git回購,我使用它提供了NSAttributedString類別。它可以讓你喜歡的東西:

NSMutableAttributedString *mystring = [[NSMutableAttributedString alloc] initWithString:@"My String"]; 
[mystring setTextColor:[UIColor colorWithRGB:78 green:111 blue:32 alpha:1]]; 
mystring.font = [UIFont systemFontOfSize:14]; 

如果你不想使用第三方lib中,檢查出this link關於如何獲得,與歸屬的字符串開始一個體面的教程。

14

斯威夫特3溶液

此外,您還可以使用,而不是在ObjC或雨燕指定索引的append功能:

let attrString = NSMutableAttributedString(string: "Presenting The Great...", 
              attributes: [ NSFontAttributeName: UIFont.systemFont(ofSize: 20) ]) 

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!", 
              attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 40) ])) 
1

在斯威夫特4,你會怎麼做:

let attrString = NSMutableAttributedString(string: "Presenting The Great...", 
             attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18)])); 

attrString.append(NSMutableAttributedString(string: "HULK HOGAN!", 
             attributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 36)])); 
相關問題