在swift中计算字符串从字符串到字符串结尾的范围

时间:2016-09-06 04:55:12

标签: swift nsrange

我有一个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)

但它没有用。

2 个答案:

答案 0 :(得分:3)

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

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)
}

enter image description here

请注意,如果字符串包含Emojis或其他Unicode字符,则NSRange无法正常工作,因此上述解决方案可能无法正常运行。

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

答案 1 :(得分: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))