我想用部分粗体的字符串设置标签的文本。我想要大胆的话都以同一封信开头,说“〜”。以字母开头的粗体字
例如,我可以有字符串,“这〜字是勇敢的,所以是〜这个”
然后标签的文本将包含字符串“字是勇敢的,所以是这“。
有谁知道是否有可能做出这样的功能?我试过如下:
func makeStringBoldForLabel(str: String) {
var finalStr = ""
let words = str.components(separatedBy: " ")
for var word in words {
if word.characters.first == "~" {
var att = [NSFontAttributeName : boldFont]
let realWord = word.substring(from: word.startIndex)
finalStr = finalStr + NSMutableAttributedString(string:realWord, attributes:att)
} else {
finalStr = finalStr + word
}
}
}
,但得到的错误:
Binary operator '+' cannot be applied to operands of type 'String' and 'NSMutableAttributedString'
就行发生错误“finalStr = finalStr + NSMutableAttributedString(字符串:realWord,属性:ATT)”,如果我投“finalStr”作为nsmutableattributedstring我得到一个错误,说我不能添加2个nsmutableattributedstrings –
啊。我更新了答案。这应该可以解决你的问题。 – Finn
问题是你不能在NSMutableAttributedStrings上使用'+'。相反,你必须使用.append()。 – Finn