我想用部分粗體的字符串設置標籤的文本。我想要大膽的話都以同一封信開頭,說「〜」。以字母開頭的粗體字
例如,我可以有字符串,「這〜字是勇敢的,所以是〜這個」
然後標籤的文本將包含字符串「字是勇敢的,所以是這「。
有誰知道是否有可能做出這樣的功能?我試過如下:
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