Reputation: 7922
I know the becomeFirstResponder
method to set a focus on a control, but how to know whether that control (for ex. UITextView
) is currently having focus on it or not ?
EDIT: the problem is that I want (for example) to change the background color of the UITextView when it receives focus, where should I put the isFirstResponder call exactly ? should I use notifications in this case ?
thanks so much in advance.
Upvotes: 26
Views: 28548
Reputation: 15147
if([txtView isFirstResponder]){
//Has Focus
} else {
//Lost Focus
}
This is UITextView's delegate method,
- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView{
//Has Focus
return YES;
}
This is lost focus
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
if ([text isEqualToString:@"\n"]){
//Lost Focus
[textView resignFirstResponder];
}
return YES;
}
Upvotes: 48
Reputation: 756
Use the UITextField delegate methods. When textField got focus the(bacame first responder)
- (void)textFieldDidBeginEditing:(UITextField *)textField;
will be fired,
and when it lost focus
- (void)textFieldDidEndEditing:(UITextField *)textField;
will be fired.
Upvotes: 6