Hash tag detection for TextViews in Swift
This is a quick and dirty sample project implementing Hashtag detection
To use this in your own app, just copy the UITextField+Extension.swift file into your project.
You may want to further customize this section of code with a TextView font and color that fits your app's style guide, because the Storyboard attributes get overridden.
To detect hashtags in your textViews:
- Make sure the UITextView is
selectable
, can detectlinks
, and is noteditable
(see image below) - Wire the UITextView delegate to your ViewController
- Implement the UITextViewDelegate method
textView:shouldInteractWithURL:
to hook into the URL tap. See example. - After you set the text, call the
resolveHashTags()
method. See example
The approach used here is to add an attribute (much like an "href") to hashtagged words.
Hashtag detection builds upon URL detection. This is why the TextView is setup to detect links. Note that links are only clickable when Editable
is unchecked.
At this point, URLs in the textview will open in the Safari app.
Next, an "href" attribute is added to each hashtagged word.
The overall process goes something like this:
- Iterate over each word and look for anything that starts with
#
- Chop off the first character
#
. For example,#helloWorld
becomeshelloWorld
- Create a fake URL using a fake URL scheme. For example,
hash:helloWorld
- Associate this fake URL with the hashtag word.
NSMutableAttributedString
has APIs to accomplish this.
Now that hashtags are URLs, they are a different color and can be clicked. Note: it's tempting to add a tap gesture to TextView, but you can leverage the built-in delegate instead.
Intercept the URL click and check for your fake URL scheme.
- Set the TextView delegate.
- Implement the
UITextFieldDelegate
which has ashouldInteractWithURL
method - Check for your fake
URL.scheme
- Grab the payload in the
URL.resourceSpecifier
- STTweetLabel, an Objective-C CocoaPod for hashtag detection
- A swift implementation of hashtags and mentions. I wish this was available when I first implemented hashtags. Their approach is slightly different though.
- I used this to initially figure out my approach. You might need to click "translate from japanese" on the top.
- I used this to figure out how to use
NSMutableAttributedString
- Ray Wenderlich Scroll View video series helped me understand keyboard movement in the example project.