gpt4 book ai didi

swift 。向多个实例添加属性

转载 作者:搜寻专家 更新时间:2023-10-31 22:45:37 25 4
gpt4 key购买 nike

我有数组,其中包含我要应用特定属性的文本术语字符串。这是一个代码片段:

static var bold = [String]()
static let boldAttribs = [NSFontAttributeName: UIFont(name: "WorkSans-Medium", size: 19)!]
for term in bold {
atStr.addAttributes(boldAttribs, range: string.rangeOfString(term))
}

这非常适合单个术语或短语的使用。但它仅适用于特定术语的首次使用。有没有办法在不求助于数值范围的情况下将属性应用于同一术语的所有实例?例如,在同一个字符串中使用粗体显示“动画按钮”。

编辑:这行得通。

// `butt2` is [String]() of substrings to attribute
// `term` is String element in array, target of attributes
// `string` is complete NAString from data
// `atStr` is final
for term in butt2 {
var pos = NSRange(location: 0, length: string.length)
while true {
let next = string.rangeOfString(term, options: .LiteralSearch, range: pos)
if next.location == NSNotFound { break }

pos = NSRange(location: next.location+next.length, length: string.length-next.location-next.length)

atStr.addAttributes(butt2Attribs, range: next)
}
}

最佳答案

您不必求助于数值范围,但您确实需要求助于循环:

// atStr is mutable attributed string
// str is the input string
atStr.beginEditing()
var pos = NSRange(location: 0, length: atStr.length)
while true {
let next = atStr.rangeOfString(target, options: .LiteralSearch, range: pos)
if next.location == NSNotFound {
break
}
atStr.addAttributes(boldAttribs, range: next)
print(next)
pos = NSRange(location: next.location+next.length, length: atStr.length-next.location-next.length)
}
atStr.endEditing()

关于 swift 。向多个实例添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38555450/

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