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

标签 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)

但它不起作用。

最佳答案

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

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


请注意,如果字符串包含表情符号或其他 Unicode 字符,NSRange 将无法正常工作,因此上述解决方案可能无法在这种情况下正常工作。

请查看以下 SO 答案以获得更好的解决方案,该解决方案也涵盖了这种情况:

关于swift - 在swift中计算从单词到字符串结尾的字符串范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39340898/

相关文章:

ios - 打字时搜索栏消失

ios - 将 isTouchInside 设置为 false

ios - iOS 13 WKWebView不再显示pdf文件

ios - 这两个范围相交吗?如果是这样,我怎么知道?

objective-c - nsrange.location 不完全是麻烦 makerange 子串 ios objective c

ios - 如何比较不区分大小写的 NSRange ?

ios - 只有最后添加的 View 在 UIScrollView iOS 中可见

ios - 在 Swift 中从 UITableViewController 发送短信

ios - 如何正确地从一个字符串中取出一个字符串?

swift - 在 NSMutableAttributedString 中查找子字符串的范围