ios 如何知道 UITextView 是否有焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11305571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to know whether a UITextView has a focus or not
提问by JAHelia
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.
非常感谢。
回答by Mehul Mistri
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;
}
回答by Boris Nikolic
Use the UITextField delegate methods. When textField got focus the(bacame first responder)
使用 UITextField 委托方法。当 textField 获得焦点时(第一响应者)
- (void)textFieldDidBeginEditing:(UITextField *)textField;
will be fired,
- (void)textFieldDidBeginEditing:(UITextField *)textField;
将被解雇,
and when it lost focus
当它失去焦点时
- (void)textFieldDidEndEditing:(UITextField *)textField;
will be fired.
- (void)textFieldDidEndEditing:(UITextField *)textField;
将被解雇。