我想用一个部分粗体的字符串设置标签的文本。我想要大胆的单词都以相同的字母开头,说“〜”。
例如,我可以使用字符串,“这个〜字是粗体,所以〜这个”
然后标签的文字将包含字符串“This word 是粗体,这个”也是如此。
有人知道是否可以制作这样的功能?我尝试了以下方法:
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'
答案 0 :(得分:0)
易于解决问题。
使用:
func makeStringBoldForLabel(str: String) {
let finalStr = NSMutableAttributedString(string: "")
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.append(NSMutableAttributedString(string:realWord, attributes:att))
} else {
finalStr.append(NSMutableAttributedString(string: word))
}
}
}
答案 1 :(得分:0)
错误消息很明确,您无法将String
和NSAttributedString
与+
运算符连接起来。
您正在寻找API enumerateSubstrings:options
。它通过.byWords
选项逐字枚举字符串。不幸的是,波浪号(~
)不被识别为单词分隔符,因此我们必须检查单词是否具有前面的波形符号。然后更改特定范围的字体属性。
let string = "This ~word is bold, and so is ~this"
let attributedString = NSMutableAttributedString(string: string, attributes:[NSFontAttributeName : NSFont.systemFont(ofSize: 14.0)])
let boldAttribute = NSFont.boldSystemFont(ofSize: 14.0)
string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) { (substring, substringRange, enclosingRange, stop) -> () in
if substring == nil { return }
if substringRange.lowerBound != string.startIndex {
let tildeIndex = string.index(before: substringRange.lowerBound)
if string[tildeIndex..<substringRange.lowerBound] == "~" {
let location = string.distance(from: string.startIndex, to: tildeIndex)
let length = string.distance(from: tildeIndex, to: substringRange.upperBound)
attributedString.addAttribute(NSFontAttributeName, value: boldAttribute, range: NSMakeRange(location, length))
}
}
}