ios - 更改字符串中特定单词的颜色

标签 ios swift nsattributedstring

我正在尝试更改以 @ 开头的特定单词的颜色,但是我在下面的代码中不断收到错误消息。

据我所知,它似乎与范围变量有关。

我收到以下错误:

cannot invoke 'addAttribute' with an argument list of type (String, value: UIColor, range Range?)

代码:

var messageMutableString = NSMutableAttributedString(string: message, attributes: [NSFontAttributeName:UIFont(name: "PT Sans", size: 13.0)!])

var words = message.componentsSeparatedByString(" ")

for word in words {
    if word.hasPrefix("@") {
        var range = message.rangeOfString(word)
        messageMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor(rgba: "#B52519"), range: range)
    }
}

最佳答案

addAttribute 采用 NSRange。尝试使用以下内容:

let range = (message as NSString).rangeOfString(word)

附注如果可能,最好使用 let 而不是 var

关于ios - 更改字符串中特定单词的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30422076/

相关文章:

ios - 我需要为 iPhone 和 iPad 设置单独的主界面,但是 Xcode 只允许我为项目设置一个通用界面

ios - 无法让 DispatchGroup 在 Swift 中正常工作

ios - 如何将带有表单数据的图像上传到api参数上的图像?

swift - 比较 Swift String 和 NSAttributedString

ios - 使用从 HTML 构建的 NSAttributedString 时在 iOS7/8 UITextView 中进行字距调整

ios - MkMapView 缩放级别

iphone - 如何使用 Mobile Safari 中的链接使用 Twitter 应用程序打开用户的 Twitter 个人资料?

ios - 在 UITableViewCell 内渲染 UIWebView

ios - 使用 Storyboard segues 将 View Controller 从模态推送到模态父级使用的导航 Controller

ios - 枚举可变属性字符串(下划线按钮)