Search code examples
swiftuitextfieldnsattributedstringnsrange

Get NSAttributedString from UITextField within NSRange


Let's assume I have this code:

let string = "This is a <b>bold</b> text"
let data = Data(string.utf8)
let attributedText = try! NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
textField.attributedText = attributedText

Result: This is a bold text

Now my textField is editable, and let's say I have my cursor here:

This is a bold tex|t

You can see my cursor between x and t

I have a variable called cursorPosition where I store the cursor position anytime it changes and in this current case, the value of cursorPosition will be 18

Now my question: Is there a possible way I can get all the NSAttributedString using NSRange. So I want to get all NSAttributedString before my cursor position using 0..<cursorPosition and the result will be:

This is a <b>bold</b> tex

And not

This is a bold tex

Solution

  • You can get an attributed substring of an NSAttributedString using the attributedSubstring method.

    let attrStr: NSAttributedString = ... // some attributed string
    let range = NSRange(location: 0, length: someLength)
    let attrSubStr = attrStr.attributedSubstring(from: range)
    

    But this is not going to give you an HTML string. This is going to give you another NSAttributedString representing the desired range. If you want HTML then you need to take extra steps to convert the attributed string into HTML.