我尝试在代码中设置字符串的某些属性,但无法使NSAttributedString
起作用。这是函数,它应该改变字符串:
func getAttributedString(string: String) -> NSAttributedString
{
var attrString = NSMutableAttributedString(string: string)
var attrs = [NSFontAttributeName : UIFont.boldSystemFontOfSize(18.0)]
attrString.setAttributes(attrs, range: NSMakeRange(0, attrString.length))
return attrString
}
这就是我使用它的方式:
if (self.product.packageDimensions != nil) {
self.descriptionLabel.text =
self.descriptionLabel.text + self.getAttributedString("Package dimensions:").string +
"\n\(self.product.packageDimensions) \n"
}
但字体保持不变。我究竟做错了什么 ?
答案 0 :(得分:3)
您在代码中犯了2个错误。
setAttributes
需要词典,而不是数组 string
属性时,您只会获得String
,所有属性都会丢失。要向attributesString添加或更改属性,必须可变。您只能从NSMutableString
属性中获得attributedText
。如果要更改它,请从中创建一个可变版本并进行更改。然后,您可以将attributedText设置为新的可变版本。
如果您可以将属性字符串作为参数,我将为您提供一个有效的示例:
func setFontFor(attrString: NSAttributedString) -> NSMutableAttributedString {
var mutableAttrString: NSMutableAttributedString = NSMutableAttributedString(attributedString: attrString)
let headerStart: Int = 0
let headerEnd: Int = 13
mutableAttrString.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFontOfSize(18.0), range: NSMakeRange(headerStart, headerEnd))
return mutableAttrString
}
myLabel.attributedText = setFontFor(myLabel.attributedText)
正如您所看到的,我使用了attributedText
类的UILabel
属性,它也适用于UITextView
和其他人。如果您有另一个标签,则可以使用初始化程序NSAttributedString(normalString)
创建一个新的NSAttributedString,如您在问题代码中使用的那样。
答案 1 :(得分:1)
if (self.product.packageDimensions != nil) {
self.descriptionLabel.attributedText =
self.descriptionLabel.attributedText + self.getAttributedString("Package dimensions:").string +
"\n\(self.product.packageDimensions) \n"
}
您应该使用attributedText
method