Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView hide keyboard in iphone

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!

like image 354
jerrymouse Avatar asked Jul 13 '11 14:07

jerrymouse


2 Answers

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

like image 165
Roger C S Wernersson Avatar answered Oct 07 '22 13:10

Roger C S Wernersson


You need to write code in UITextViewDelegate and assign it to your class.

like image 32
Abdurrashid Khatri Avatar answered Oct 07 '22 12:10

Abdurrashid Khatri