0

I have a UITextView and using NSRegularExpression. I'm finding names in my text view. So I'm able to highlight matches using this code:

for match in matches as [NSTextCheckingResult] {
    let matchRange = match.range
    attributedText.addAttribute(NSStrokeColorAttributeName, value: UIColor.blueColor(), range:  matchRange)
}

I want to make it clickable and pass its text to a new view controller. Or maybe change it to a UIButton with the same text and add a segue to the new view controller. I'm not sure how to do it correctly.

Brian
  • 14,610
  • 7
  • 35
  • 43
user528432
  • 411
  • 2
  • 5
  • 18

2 Answers2

0

UITextView doesn't really have functionality for that. You could try your UIButton approach but you'll have trouble with links that wrap on multiple lines.

Two possible solutions:

  1. You may be able to force its URL handling functionality to do what you want - see this question. This will depend on your NSRegularExpression.
  2. You might want to try replacing your text view with TTTAttributedLabel or a similar third-party library that handles this for you. I think this is the most flexible option, and my recommended approach.
Community
  • 1
  • 1
Aaron Brager
  • 65,323
  • 19
  • 161
  • 287
  • looks like it doesn't handle segues, it works with only links? I want to open the matched word in new vc – user528432 Jan 24 '15 at 15:20
  • You can push a segue when a link is tapped in `shouldInteractWithURL:inRange:`, if you can get links to work, but otherwise you'll have to go with #2. – Aaron Brager Jan 25 '15 at 00:07
  • this looks pretty cool https://github.com/evilBird/HBVLinkedTextView but its objective c – user528432 Jan 25 '15 at 10:35
0

For future googlers, you could use NSLinkAttributeName

attributedText.addAttribute(NSLinkAttributeName, value: "\(your_value)", range: matchRange)
Steve
  • 959
  • 1
  • 11
  • 23