2016-09-06 72 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 
相关问题