快速计算从单词到字符串末尾的字符串范围

问题描述 投票:0回答:3

我有一个 NSMutatableString:

var string: String = "Due in %@ (%@) $%@.\nOverdue! Please pay now %@"
attributedText = NSMutableAttributedString(string: string, attributes: attributes)

如何在 swift 中计算单词

Overdue
的长度和起始索引?

到目前为止我已经尝试过:

let startIndex = attributedText.string.rangeOfString("Overdue")
let range = startIndex..<attributedText.string.finishIndex

// Access the substring.
let substring = value[range]
print(substring)

但这不起作用。

swift nsrange
3个回答
6
投票

您应该首先生成结果字符串:

let string = String(format: "Due in %@ (%@) $%@.\nOverdue! Please pay now %@", "some date", "something", "15", "some date")

然后使用

.disTanceTo
获取索引之间的距离;

if let range = string.rangeOfString("Overdue") {
  let start = string.startIndex.distanceTo(range.startIndex)
  let length = range.startIndex.distanceTo(string.endIndex)

  let wordToEndRange = NSRange(location: start, length: length) 
  // This is the range you need

  attributedText.addAttribute(NSForegroundColorAttributeName, 
     value: UIColor.blueColor(), range: wordToEndRange)
}


请注意,如果字符串包含表情符号或其他 Unicode 字符,

NSRange
将无法正常工作,因此上述解决方案可能无法在这种情况下正常工作。

请查看以下 SO 答案,以获得也涵盖该案例的更好解决方案:


0
投票

看这个,

                let nsString = element.text as NSString
                let range = nsString.range(of: word, options: .widthInsensitive)
                let att: [NSAttributedString.Key: Any] = [.foregroundColor: UIColor.systemBlue]
                attText.addAttributes(att, range: NSRange(location: range.location, length: range.length))

0
投票

Mahadev Prabhu 答案的基础:

extension String {
    func getRange(of word: String)-> NSRange {
        return (self as NSString).range(of: word, options: .widthInsensitive)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.