7

I would like to highlight a part of text in a UITextView like Pages for iOS or Safari for iOS do. I search the documentation but I can't find a way to do it, maybe because I'm a beginner in iOS development and I miss some crucial info. Somebody can help me?

Screenshot of Pages for iOS:

Pages for iOS

Screenshot of Safari for iOS:

Safari for iOS

Wain
  • 118,658
  • 15
  • 128
  • 151
Cue
  • 2,952
  • 3
  • 33
  • 54
  • 1
    Did you try this out? http://stackoverflow.com/questions/26454037/uitextview-text-selection-and-highlight-jumping-in-ios-8 – Vishnu gondlekar Jun 18 '16 at 10:16
  • I Vishnu gondlekar, thank you for the link. I'd rather avoid setting NSAttributedString, I would like to use some highlighting functionality if possible... – Cue Jun 18 '16 at 11:16
  • Hi Vishnu, a comment of Duncan C make me understand that there is not an easy solution accessible due to my lack of knowledge of the Text kit, so at the end I used NSAttributedString how you suggested: ’mainTextField.textStorage?.setAttributedString(attributedText.copy() as! NSAttributedString)’ Thank you. – Cue Aug 10 '17 at 12:59

1 Answers1

1

If you only need to highlight a single, contiguous block of text you can set the selection programmatically. Your examples show multiple discontinuous parts however. For that you are going to need to use an attributed string. There is no other system-provided highlighting function. (There might be a third party library that offers this though - you'll have to search.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thank you for your answer Duncan C. I read [this tutorial](https://www.raywenderlich.com/86205/nsregularexpression-swift-tutorial) where the author says: "Note: Your app uses the NSAttributedString property of UITextView to highlight the search results. [...] You could also implement the highlighting functionality using Text Kit" so I figured that there was an alternative method. – Cue Jun 18 '16 at 15:07
  • 1
    Text kit is even lower level than attributed strings. Yes, you could do that but I wouldn't recommend it. – Duncan C Jun 18 '16 at 18:23