I'd building an app that uses hashtags, like Twitter or Tweetbot. When you're typing a message, if you type the hashtag symbol, I'd like to suggest tags that match the current one you're typing.
I've already figured out how to get the UITableView to appear and show a list of hashtags, but what I can't figure out is how to do the following:
- Get the
NSRange
of the current word being typed, - See if that range is formatted like a hashtag (
NSRegularExpression @"#\\w\\w*"
) - (From here on out, I've got the code figured out to search for matching hashtags and show them in the UITableView)
Can anyone help me with steps 1 and 2? I've been thinking about using textViewDidChange:
, but I'm concerned that the app's performance might suffer if I'm constantly running methods every time the characters change.
Thanks!
Another way I figured out to do this is as follows.
In the
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
function I put a listener for a # being typed which begins recording the characters following the hash until the user types a space at which time it resets.If the
BOOL recordingHashTag
is set toYES
I pass thesubstring
containing the hashtag text to a function which searches a pre populated array of hashtags. If there is a match it adds that entry to a filtered array of hashtags which it uses to populate thetableview
on the fly.The final step is to insert the hash tag when the user clicks on the entry in the table.
Just don't forget to clear out your variables when a user backspaces mid hash tag.
I figured it out! I wound up using the
textViewDidChange:
andtextViewDidChangeSelection:
methods.To get the
NSRange
of the current hashtag being typed, I ran afor
loop over theNSRegularExpression
matches in the text string. From there, I usedNSLocationInRange
to find out if the current cursor position intersected any of the hashtags.Here's the code:
The
StringChecker
class is a custom one that I wrote, it just has class methods that parse the strings. I madeStringChecker
a class because the methods are used in several places in the app. Here's the method: