如何知道UITextView是否有焦点

时间:2021-09-14 20:37:36

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 ?

我知道becomeFirstResponder方法用于设置控件的焦点,但是如何知道该控件(例如UITextView)当前是否关注它呢?

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 ?

编辑:问题是我想(例如)在UITextView收到焦点时改变它的背景颜色,我应该把isFirstResponder调用放在哪里?在这种情况下我应该使用通知吗?

thanks so much in advance.

非常感谢你的帮助。

2 个解决方案

#1


37  

if([txtView isFirstResponder]){
     //Has Focus
} else {
     //Lost Focus
}

This is UITextView's delegate method,

这是UITextView的委托方法,

- (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;
}

#2


3  

Use the UITextField delegate methods. When textField got focus the(bacame first responder)

使用UITextField委托方法。当textField得到焦点时(bacame first responder)

- (void)textFieldDidBeginEditing:(UITextField *)textField; will be fired,

*)-(void)textFieldDidBeginEditing:(UITextField文本框;将被解雇,

and when it lost focus

当它失去焦点的时候

- (void)textFieldDidEndEditing:(UITextField *)textField; will be fired.

*)-(void)textFieldDidEndEditing:(UITextField文本框;将被解雇。

#1


37  

if([txtView isFirstResponder]){
     //Has Focus
} else {
     //Lost Focus
}

This is UITextView's delegate method,

这是UITextView的委托方法,

- (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;
}

#2


3  

Use the UITextField delegate methods. When textField got focus the(bacame first responder)

使用UITextField委托方法。当textField得到焦点时(bacame first responder)

- (void)textFieldDidBeginEditing:(UITextField *)textField; will be fired,

*)-(void)textFieldDidBeginEditing:(UITextField文本框;将被解雇,

and when it lost focus

当它失去焦点的时候

- (void)textFieldDidEndEditing:(UITextField *)textField; will be fired.

*)-(void)textFieldDidEndEditing:(UITextField文本框;将被解雇。