Getting type UIView

I continue to see examples that manually iterate over all subspecies of a certain type in a UIView. For example, if you want a click outside the keyboard to reject the keyboard, no matter which field is active, you can:

-(IBAction)backgroundClick:(id)sender { [myTextField resignFirstResponder]; [myOtherTextField resignFirstResponder]; // ... repeat for each of my zillion text fields. } 

Instead of something like:

 for(UIView *v in self.view.subviews) if(v.hasKeyboard) // or something like java instanceof [v resignFirstResponder]; 

Despite the fact that improvements in a particular case of the keyboard (for example, finding out who is the first responder), I'm more interested in the general case.

+4
source share
2 answers

Could you do something like

if([v isMemberOfClass:[UITextField class]]){
[v resignFirstResponder];
}

?

+6
source

Alternatively, you can iterate with

 if( [v respondsToSelector:@selector(isFirstResponder)] && [v isFirstResponder]) { [v resignFirstResponder]; break; } 

This method will only call resignFirstResponder for the current first responder and stop when the current first responder is found. It will work with UITextFields, UITextViews, etc., as well as with any future text editing options (provided that they continue to implement response methods).

For a more general case, you can use

 if( [v isKindOfClass:UITextField.class] ) { [v resignFirstResponder]; } 

For general keyboard failure, preference is given to the first, since all that interests you is the keyboard. The object claims that it will process the message (method call), so you do not really need to care about what type it is. If you really need to make sure this is a UITextField, the second option is preferable.

+2
source

All Articles