首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在NSAttributedString中使用NSAttributedString?

如何在NSAttributedString中使用NSAttributedString?
EN

Stack Overflow用户
提问于 2018-03-19 02:33:29
回答 2查看 1.7K关注 0票数 2

NSAttributed类型语句中,我希望保留现有的属性值,并给它一个新的属性值。

问题是,replacingOccurrences只可能用于字符串类型,因为每当单词出现在整个句子中时,我都想给出一个新的值。

如果我将NSAttributedString更改为字符串类型,则属性化值将被删除。我必须保持现有的价值观。

我怎么能这么做?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-19 06:37:53

为了让这件事奏效,

1.首先需要找到字符串中存在的所有重复子字符串的索引。要获得这个结果,您可以使用以下内容:https://stackoverflow.com/a/40413665/5716829

代码语言:javascript
复制
extension String {
    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex

        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }
}

2.下一步您需要将所需的属性应用于每个索引的子字符串,即

代码语言:javascript
复制
    let str = "The problem is that replacingOccurrences Hello is only possible for string types, as I want to give Hello a new value every time Hello the word appears in the entire sentence Hello."
    let indices = str.indicesOf(string: "Hello")
    let attrStr = NSMutableAttributedString(string: str, attributes: [.foregroundColor : UIColor.blue])
    for index in indices
    {
        //You can write your own logic to specify the color for each duplicate. I have used some hardcode indices
        var color: UIColor
        switch index
        {
        case 41:
            color = .orange
        case 100:
            color = .magenta
        case 129:
            color = .green
        default:
            color = .red
        }
        attrStr.addAttribute(.foregroundColor, value: color, range: NSRange(location: index, length: "Hello".count))
    }

截图:

如果你还面临任何问题请告诉我。快乐编码..。

票数 0
EN

Stack Overflow用户

发布于 2018-03-19 03:14:06

您可以使用replaceCharacters。您可以找到要删除的子字符串的范围,并将其用作您的范围。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49355019

复制
相关文章

相似问题

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