Sunday, August 17, 2014

How to hide keyboard when losing Text Field focus in iOS/iPhone/iPad programming in Objective C when using a UIScrollView

If you are making an iOS/iPhone/iPad app, and you are trying to hide the keyboard when clicking outside the UITextField, you can do this:

1) Make sure that your UITextField has an IBOutlet in the ViewController.h file.  If you need to set this up, open the "Assistant editor", click on the storyboard, make sure that the ViewController.h file is in the other window, and Ctrl-drag the UITextField down to the ViewController.h file.

2) Make sure that the Scroll View has a delegate connected to the View Controller.  If you need to set this up, click on the Scroll View, open the "Connections inspector", and drag the circle next to the delegate to the View Controller in the "View Controller Scene" menu

3) In your ViewController.m file, add in a function that looks like this:


-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_myTextField endEditing:YES];
}

4) Instead of _myTextField, use whatever name you used in step 1 above.

No comments: