问题: NSAttributedString接受NSRange,而我正在使用使用范围的Swift字符串
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: substringRange)
}
})
会产生以下错误:
范围错误:‘attributedString.addAttribute(NSForegroundColorAttributeName,’不能转换为'NSRange‘值: NSColor.redColor(),range: substringRange)
发布于 2016-02-02 13:09:13
对于你描述的这种情况,我发现这是可行的。它相对简短而甜蜜:
let attributedString = NSMutableAttributedString(string: "follow the yellow brick road") //can essentially come from a textField.text as well (will need to unwrap though)
let text = "follow the yellow brick road"
let str = NSString(string: text)
let theRange = str.rangeOfString("yellow")
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: theRange)
发布于 2017-09-25 20:19:01
答案很好,但是使用Swift 4你可以简化你的代码:
let text = "Test string"
let substring = "string"
let substringRange = text.range(of: substring)!
let nsRange = NSRange(substringRange, in: text)
要小心,因为range
函数的结果必须被解包。
发布于 2014-11-20 21:33:16
可能的解决方案
Swift提供了NSRange(),它测量起点和终点之间的距离,可用于创建距离:
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
// println("word: \(substring) - \(d1) to \(d2)")
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
https://stackoverflow.com/questions/27040924
复制相似问题