首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >斯威夫特。向多个实例添加属性

问斯威夫特。向多个实例添加属性
EN

Stack Overflow用户
提问于 2016-07-24 18:36:57
回答 1查看 747关注 0票数 3

我的arrays包含要应用特定属性的文本术语的字符串。下面是代码片段:

代码语言:javascript
复制
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))
}

这对于单个术语或短语的使用非常有用。但它只适用于特定术语的第一次使用。是否有一种方法,不诉诸于数值范围,将属性应用于同一术语的所有实例?例如,在相同的字符串粗体中使用“动画按钮”。

编辑:这是可行的。

代码语言:javascript
复制
// `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)
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-07-24 19:02:21

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

代码语言:javascript
复制
// 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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38555450

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档