首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自Swift Range的NSRange?

来自Swift Range的NSRange?
EN

Stack Overflow用户
提问于 2014-11-20 21:33:16
回答 12查看 144.1K关注 0票数 195

问题: NSAttributedString接受NSRange,而我正在使用使用范围的Swift字符串

代码语言:javascript
运行
复制
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)

EN

回答 12

Stack Overflow用户

发布于 2016-02-02 13:09:13

对于你描述的这种情况,我发现这是可行的。它相对简短而甜蜜:

代码语言:javascript
运行
复制
 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)
票数 59
EN

Stack Overflow用户

发布于 2017-09-25 20:19:01

答案很好,但是使用Swift 4你可以简化你的代码:

代码语言:javascript
运行
复制
let text = "Test string"
let substring = "string"

let substringRange = text.range(of: substring)!
let nsRange = NSRange(substringRange, in: text)

要小心,因为range函数的结果必须被解包。

票数 43
EN

Stack Overflow用户

发布于 2014-11-20 21:33:16

可能的解决方案

Swift提供了NSRange(),它测量起点和终点之间的距离,可用于创建距离:

代码语言:javascript
运行
复制
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)
        }
})
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27040924

复制
相关文章

相似问题

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