Calculate range of string from word to end of string in swift
Asked Answered
S

3

3

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.

Stoffel answered 6/9, 2016 at 4:55 Comment(0)
A
6

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

enter image description here


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:

Afoul answered 6/9, 2016 at 5:1 Comment(2)
Genius. Solved 2 of my problems by adding the color. Thank you so much @ozgur! Wish I could double up vote. – Stoffel
This conversion of string indices to NSRange does not work correctly if the string contains Emojis or other Unicode characters > U+FFFF. Compare #27881150 and https://mcmap.net/q/23791/-nsrange-from-swift-range for similar issues. – You can try it with let string = "πŸ˜€πŸ˜€πŸ˜€ Bla bla Overdue! bla bla" – Sunless
F
0

Look at this,

                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))
Flinch answered 1/7, 2021 at 8:25 Comment(1)
Please add some explanation. Why do you think your proposed solution might help the OP. – Nonobedience
S
0

Base of the Mahadev Prabhu's answer:

extension String {
    func getRange(of word: String)-> NSRange {
        return (self as NSString).range(of: word, options: .widthInsensitive)
    }
}
Shovelboard answered 7/3 at 18:18 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.