gpt4 book ai didi

swift - 以字母开头的粗体单词

转载 作者:行者123 更新时间:2023-11-30 12:31:02 25 4
gpt4 key购买 nike

我想用部分粗体的字符串设置标签的文本。我想要加粗的单词都以同一个字母开头,比如“~”。

例如,我可以使用字符串“This ~word is bold, and so is ~this”

然后标签的文本将包含字符串“这个单词是粗体,这个也是粗体”。

有谁知道是否可以实现这样的功能?我尝试了以下方法:

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
}
}
}

但出现错误:

二元运算符“+”不能应用于“String”和“NSMutableAttributedString”类型的操作数

最佳答案

轻松解决问题。

用途:

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))
}
}
}

关于swift - 以字母开头的粗体单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43557044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com