I want to hide keyboard when a user presses return in UITextView
object in iphone. However, mysteriously this is not working for UITextView
but working for UITextField
. I am unable to figure out why...
This is what I did:
1) I created a view based application in XCode4.
2) in .xib created UITextView
, UITextField
and UIButton
objects
3) Marked both UITextField
and UITextView
delegates to File's Owner in Outlets
4) Added <UITextFieldDelegate>
to @interface UIViewController in .h
5) Added textFieldShouldReturn
function in .m
Here are the codes:
.h file
@interface keyboardDisappearViewController : UIViewController <UITextFieldDelegate>
{
UITextView *textBoxLarge;
UITextField *textBoxLittle;
}
@property (nonatomic, retain) IBOutlet UITextView *textBoxLarge;
@property (nonatomic, retain) IBOutlet UITextField *textBoxLittle;
- (IBAction)doSomething:(id)sender;
@end
.m file
- (BOOL) textFieldShouldReturn:(UITextField *)theTextField
{
NSLog(@"textFieldShouldReturn Fired :)");
[textBoxLarge resignFirstResponder];
[textBoxLittle resignFirstResponder];
return YES;
}
Amazingly, the keyboard is disappearing in case of textBoxLittle (UITextField) but not in case of textBoxLarge(UITextView)
As a further check I, made the button to call function doSomething
- (IBAction)doSomething:(id)sender {
[textBoxLarge resignFirstResponder];
[textBoxLittle resignFirstResponder];
}
When I am pressing the button, keyboard is disappearing in both textboxes.
Its driving me nuts why textFieldShouldReturn is working for small textbox, but NOT for large textbox.
Please Help!
Three things:
Make your view implement UITextViewDelegate.
@interface keyboardDisappearViewController : UIViewController
<UITextFieldDelegate, UITextViewDelegate>
Add the following method:
- (BOOL)textView:(UITextView *)textView
shouldChangeTextInRange:(NSRange)range
replacementText:(NSString *)text
{
if ([text isEqualToString:@"\n"])
{
[textView resignFirstResponder];
}
return YES;
}
Set the file's owner as delegate for the UITextView in the interface builder.
(BTW: Solution copied from the comments to the previous answer, as it took me a while to extract. I though others could benefit from my experience.)