NSAttributedString 中的颜色标签 [英] color hashtags in NSAttributedString

查看:39
本文介绍了NSAttributedString 中的颜色标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标签,其中包含普通文本和主题标签.我希望主题标签具有不同的颜色,所以我做了这样的事情:

I have a label where I have normal text and hashtags. I wanted the hashtags to have a different color, so I did something like this:

let text = "#hellothere I am you. #hashtag #hashtag2 @you #hashtag3"
        let words = text.components(separatedBy: " ")
        let attribute = NSMutableAttributedString.init(string: text)
        for word in words {
            let range = (text as NSString).range(of: word)
            if word.hasPrefix("#") {
                attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range)
            }
        }
        label.attributedText = attribute

然而,当我使用这个逻辑时,结果不一致.有时,主题标签会按预期着色,有时,包含主题标签的单词的某些部分会与下一个单词的某些部分一起着色.我正在寻找一个解决方案,我可以识别单词中是否有#"字符(仅在单词中第一次出现),然后从主题标签为单词着色,直到下一个空格、逗号、分号、句号或字符串结尾,以适用者为准.

However, when i am using this logic, the results are inconsistent. Sometimes, the hashtags get colored as expected, other times some portion of the word containing the hashtag gets colored along with some portion of the next word. I am looking for a solution where I can identify if there is a "#" character in the word (the first occurrence in the word only) and then color the word from the hashtag till the next whitespace, comma, semicolon, full stop or end of string, whichever may be applicable.

推荐答案

这需要正则表达式.Swift 3 中的示例.

This calls for a regular expression. Example in Swift 3.

let attrStr = NSMutableAttributedString(string: "#hellothere I am you. #hashtag, #hashtag2 @you #hashtag3")
let searchPattern = "#\\w+"
var ranges: [NSRange] = [NSRange]()

let regex = try! NSRegularExpression(pattern: searchPattern, options: [])
ranges = regex.matches(in: attrStr.string, options: [], range: NSMakeRange(0, attrStr.string.characters.count)).map {$0.range}

for range in ranges {
    attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellow, range: NSRange(location: range.location, length: range.length))
}

attrStr

将上述内容粘贴到操场上并查看输出.要查看正在运行的正则表达式,请尝试此链接.

Paste the above into a playground and look at the output. To see the regex in action try this link.

这篇关于NSAttributedString 中的颜色标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆