/SwiftTextViewHashtag

Hash tag detection for TextViews in Swift

Primary LanguageSwift

SwiftTextViewHashtag

Hash tag detection for TextViews in Swift

Overview

This is a quick and dirty sample project implementing Hashtag detection

animated gif demo

Installation / Integration

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.

Usage

To detect hashtags in your textViews:

  1. Make sure the UITextView is selectable, can detect links, and is not editable (see image below)
  2. Wire the UITextView delegate to your ViewController
  3. Implement the UITextViewDelegate method textView:shouldInteractWithURL: to hook into the URL tap. See example.
  4. After you set the text, call the resolveHashTags() method. See example

screenshot from storyboard

How it works

The approach used here is to add an attribute (much like an "href") to hashtagged words.

URL detection

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.

Add link attributes

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 becomes helloWorld
  • 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.

Here's the code

Clicking on hashtags

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 a shouldInteractWithURL method
  • Check for your fake URL.scheme
  • Grab the payload in the URL.resourceSpecifier

Here's the code

Other resources

  • 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.