Resigning from a list of UITextFields

Usually if you want to hide the keyboard, you click anywhere else on the view, the action that happens at this point is -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event or if you're using something along the lines of a UIScrollView, you'll need to set up a TapGesture. Once you've created this method the standard code to include is the following:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
	for (UIView *view in [self.view subviews]) {
		if ([view isKindOfClass:[UITextField class]]) {
			UITextField *textField = (UITextField *)view;
			[textField resignFirstResponder];

There are a number of problems with this, the main one being that it is very inefficient, and if for any reason there are UITextFields within other views, you have to go more levels deep with the for (UIView *view in [self.view subviews]) function.

Speaking to some helpful developers on #iphonedev on Freenode they suggested that it's better practice to just keep a log of what is currently being edited, and use that.

To do this in your .h file include the following: UITextField *editingField; and also make sure that you have UITextFieldDelegate set up. Then, within the .m file you need to add the following method:

- (void)textFieldDidBeginEditing:(UITextField *)textField { editingField = textField; }

Note: This will only work if your UITextFields have the setDelegate:self.

Then one last function to add is the following:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
	[editingField resignFirstResponder];

And that is all that there is to it, as soon as you tap, it works out who was last, or currently being edited, and then resigns that as the first responder, therefore hiding the Keyboard.

I hope this helps!