Editable UITextView with Links

A number of users requested that they be able to add notes to a meal in MealPlan, and users have also requested being able to add links. I wanted to add a single field for notes, which could include one or more links. The note field would need to be editable, but the links also need to be clickable.

UITextView supports both these things, but not at the same time.

I wanted this when viewing:

201205041639-1
But when you tap to edit, the field becomes editable.

201205041639
Turns out this is very easy to set up.

In a nutshell, you install a tap gesture recogniser on the view that, when a users taps on it, makes it editable and assigns keyboard focus to it. The tap gesture recogniser is triggered when the user taps anywhere on the field, but if the user taps and holds on the link, they are given the opportunity to open it.

201205041641

Setting this up requires a gesture recogniser on the UITextView that makes the field editable and transfers focus to it when the user taps on it, and requires that your UITextViewDelegate set the field back to non-editable when the user is done editing. Here’s code that accomplishes all these things.

[cc lang=”objc”]
// Add the tap gesture recogniser to the view.
– (void)configureTextView {
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(textViewTapped:)];
textView.editable = NO;
textView.dataDetectorTypes = UIDataDetectorTypeLink;
[textView addGestureRecognizer:recognizer];
}

// Notification from the recogniser that the UITextView was tapped
– (void)textViewTapped:(UIGestureRecognizer *)recognizer {
UITextView *textView = (UITextView *)recognizer.view;
textView.editable = YES;
[textView becomeFirstResponder];
}

// UITextViewDelegate method
– (void)textViewDidEndEditing:(UITextView *)textView {
textView.editable = NO;
}
[/cc]