Calculate range of string from word to end of string in swift

随声附和 提交于 2019-12-24 01:25:30

问题


I have an NSMutatableString:

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

How to calculate both the length and starting index from the word Overdue in swift?

so far I have tried:

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

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

But it doesn't work.


回答1:


You should generate the resulting string first:

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

Then use .disTanceTo to get the distance between indices;

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


Please do note that NSRange does not work correctly if the string contains Emojis or other Unicode characters so that the above solution may not work properly for that case.

Please look at the following SO answers for a better solution which cover that case as well:

  • https://stackoverflow.com/a/27041376/793428
  • https://stackoverflow.com/a/27880748/793428


来源:https://stackoverflow.com/questions/39340898/calculate-range-of-string-from-word-to-end-of-string-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!