26

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

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

非常感谢。

4

2 回答 2

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

这是 UITextView 的委托方法,

- (BOOL)textViewShouldBeginEditing:(UITextView *)aTextView{
    //Has Focus
    return YES;
}

这是失去焦点

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        //Lost Focus
        [textView resignFirstResponder];
    }
    return YES;
}
于 2012-07-03T06:36:22.677 回答
6

使用 UITextField 委托方法。当 textField 获得焦点时(成为第一响应者)

- (void)textFieldDidBeginEditing:(UITextField *)textField;会被解雇,

当它失去焦点时

- (void)textFieldDidEndEditing:(UITextField *)textField;将被解雇。

于 2017-03-17T09:18:33.077 回答