2016-09-06 76 views
1

我想在我的UILabel中設置屬性文本。它應該是2行。所以我做了2個這樣的屬性字符串。如何在UILabel中設置2行屬性字符串

var myMutableTitle = NSMutableAttributedString(string: title!, attributes: [NSFontAttributeName:UIFont.init(name: fontBold, size: 15.0)!]) 
var mutDj=NSMutableAttributedString(string: dj!, attributes: [NSFontAttributeName:UIFont.init(name: font, size: 15.0)!]) 

如何添加這兩個屬性串到2線,如

Title 
DJ name 

請幫我顯示。 感謝

回答

2

添加\ n到第二屬性文本

var myMutableTitle = NSMutableAttributedString(string: title!, attributes: [NSFontAttributeName:UIFont.init(name: fontBold, size: 15.0)!]) 
var mutDj= NSMutableAttributedString(string: "\n \(dj)", attributes: [NSFontAttributeName:UIFont.init(name: font, size: 15.0)!]) 
myMutableTitle.appendAttributedString(mutDj) 

yourLabel.numberOfLines = 0 
yourLabel.attributedText = myMutableTitle 
+0

謝謝,但即時通訊有一個小問題,這個DJ名稱來作爲可選(「DJ的名稱」)我該如何解決這個問題? – Irrd

+0

只需加\(dj!) –

2

而不是創建2 NSMutableAttributedString你可以創建一個單一的像這樣的。

let str1 = "\(title!) \n(dj!)" 
let attributedStr = NSMutableAttributedString(string: str1) 
attributedStr.addAttribute(NSFontAttributeName, value: UIFont.init(name: fontBold, size: 15.0)!, range: (str1 as NSString).rangeOfString(title!)) 
attributedStr.addAttribute(NSFontAttributeName, value: UIFont.init(name: font, size: 15.0)!, range: (str1 as NSString).rangeOfString(dj!)) 
label.attributedText = attributedStr 
相關問題