1

Possible Duplicate:
Dismiss keyboard on touch anywhere outside UITextField

I am using UIScrollView in my app. I am putting few text fields and button. I want to hide my keyboard when they touch outside of the textbox. (I mean they will be taping on the uiscrollview). I have tried a lot of things... I use UIGestureRecognizer but its not working... help please

Community
  • 1
  • 1
dcprog
  • 135
  • 1
  • 12

2 Answers2

2

Here's the solution just tried and it works.. Hope helps

Add the following code to your viewDidLoad;

-(void)viewDidLoad {
    //create a tapGesture which calls a removeKeyboard method
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeKeyboard)];

    tapGesture.cancelsTouchesInView = NO;

    [self.yourScrollView addGestureRecognizer:tapGesture];
}

-(void)removeKeyboard {
    [self.yourTextField resignFirstResponder];
}

Hope helps....

AndyDev
  • 1,409
  • 10
  • 17
lionserdar
  • 2,022
  • 1
  • 18
  • 21
1

Try the following code in your view...

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    if ([yourTextView isFirstResponder] && [touch view] != yourTextView) {
        [yourTextView resignFirstResponder];
    }
}
AndyDev
  • 1,409
  • 10
  • 17
  • Its not working... i copied the code and tried it with my text box. But its not working. Instead of yourTextView, I used my textFieldName. – dcprog Oct 01 '12 at 20:57
  • your code has [touch view], but I am using UIScrollview that covers the entire UIView – dcprog Oct 01 '12 at 21:00
  • Is your view set up to be the delegate of your UITextField? – AndyDev Oct 01 '12 at 21:03
  • I set scrollview.delegate = self; Is this right way to set the scrollview as delegate? Or should I change it to view instead? How can i set UIView as my delegate? – dcprog Oct 01 '12 at 21:17
  • Your TextField(s) need the delegate setting to the Files Owner (the view). You can do this in Interface Builder by dragging delegate to "Files Owner" like in this screenshot. http://cl.ly/image/3v2D0q0u1r0T – AndyDev Oct 01 '12 at 21:20
  • i changed it but its still not working. My text box is in UIScrollView. Not the UIView. My UIScrollView Covers the UIView Completely... UIView is behind UIScrollView... So I can tap only the scrollview – dcprog Oct 01 '12 at 21:37
  • That should work fine re: ScrollView, also ensure you have added to your .h file. – AndyDev Oct 01 '12 at 21:44