问题: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)
}
})
产生以下错误:
错误:'Range'不能转换为'NSRange'
attributedString。addAttribute(NSForegroundColorAttributeName,值:NSColor.redColor(),范围:substringRange)
我的解决方案是一个字符串扩展,首先获得快速范围,然后获得从字符串的开始到子字符串的开始和结束的距离。
然后使用这些值计算子字符串的开始和长度。然后我们可以将这些值应用到NSMakeRange构造函数。
这个解决方案适用于由多个单词组成的子字符串,这里使用enumerateSubstrings的许多解决方案让我失望。
extension String {
func NSRange(of substring: String) -> NSRange? {
// Get the swift range
guard let range = range(of: substring) else { return nil }
// Get the distance to the start of the substring
let start = distance(from: startIndex, to: range.lowerBound) as Int
//Get the distance to the end of the substring
let end = distance(from: startIndex, to: range.upperBound) as Int
//length = endOfSubstring - startOfSubstring
//start = startOfSubstring
return NSMakeRange(start, end - start)
}
}
我的解决方案是一个字符串扩展,首先获得快速范围,然后获得从字符串的开始到子字符串的开始和结束的距离。
然后使用这些值计算子字符串的开始和长度。然后我们可以将这些值应用到NSMakeRange构造函数。
这个解决方案适用于由多个单词组成的子字符串,这里使用enumerateSubstrings的许多解决方案让我失望。
extension String {
func NSRange(of substring: String) -> NSRange? {
// Get the swift range
guard let range = range(of: substring) else { return nil }
// Get the distance to the start of the substring
let start = distance(from: startIndex, to: range.lowerBound) as Int
//Get the distance to the end of the substring
let end = distance(from: startIndex, to: range.upperBound) as Int
//length = endOfSubstring - startOfSubstring
//start = startOfSubstring
return NSMakeRange(start, end - start)
}
}
可能的解决方案
Swift提供了distance()来测量开始和结束之间的距离,可以用来创建一个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)
}
})