Use a UILongPressGestureRecognizer
and a UITextView
.
Add a UILongPressGstureRecognizer
property to your view controller:
@property UILongPressGestureRecognizer *gestureRecognizer;
You need to declare that your view controller conforms to the UITextViewDelegate
and UIGestureRecognizerDelegate
protocols:
@interface ViewController : UIViewController<UITextViewDelegate, UIGestureRecognizerDelegate>
In viewDidLoad
:
self.textView.editable = NO;
self.textView.delegate = self;
self.gestureRecognizer = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(textViewLongPressed:)];
self.gestureRecognizer.delegate = self;
[self.textView addGestureRecognizer:self.gr];
This is the method that will be called when you long press the text view:
-(void) textViewLongPressed:(UILongPressGestureRecognizer *)sender
{
self.textView.editable = YES;
[self.textView becomeFirstResponder];
}
Implement this method from the UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
if (self.gestureRecognizer == gestureRecognizer){
return YES;
}
return NO;
}
When you finish editing the text view
-(void) textViewDidEndEditing:(UITextView *)textView
{
self.textView.editable = NO;
}
To dismiss the keyboard when you press return:
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"])
[textView resignFirstResponder]; // or [textView endEditing:YES]
return YES;
}