如何将文本字段添加到inputAccessoryView并使textView作为第一响应者 [英] How to add text field to inputAccessoryView and make the textView first responder
问题描述
我的代码:
- (void)viewDidLoad {
[super viewDidLoad];
CGRect rectFake = CGRectZero;
UITextField *fakeField = [[UITextField alloc] initWithFrame:rectFake];
[self.view addSubview:fakeField];
UIView *av = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 39.0)];
av.backgroundColor = [UIColor darkGrayColor];
CGRect rect = CGRectMake(200.0, 4.0, 400.0, 31.0);
UITextField *textField = [[UITextField alloc] initWithFrame:rect];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.font = [UIFont systemFontOfSize:24.0];
textField.delegate = self;
[av addSubview:textField];
fakeField.inputAccessoryView = av;
[fakeField becomeFirstResponder];
}
我试图添加
[textField becomeFirstResponder]
at结束,但它没有用。
at the end, but it does no work.
当按下ENTER时委托方法隐藏键盘的另一个问题也不起作用。
Another problem that delegate method to hide keyboard when ENTER is pressed does not work also.
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
推荐答案
我正面临同样的挑战。您的(和我的初始)方法可能不起作用,因为 inputAccessoryView
中的文本字段拒绝成为第一响应者,因为 UITextField
最初不在您的屏幕上。
I was facing the same challenge. Your (and my initial) approach probably don't work because the text field in the inputAccessoryView
refuses to become first responder as the UITextField
is not located on your screen initially.
我的解决方案:检查键盘(以及附件视图)何时出现!
My solution: check when the keyboard (and with that the accessory view) appear!
步骤1)听取通知(确保在您想要接收通知之前执行此代码)。
Step 1) Listen for the notification (make sure this code is executed before you want to receive the notification).
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeFirstResponder)
name:UIKeyboardDidShowNotification
object:nil];
步骤2)当键盘出现时,您可以在 inputAccessoryView
成为第一响应者:
Step 2) When the keyboard has appeared, you can set the textfield in your inputAccessoryView
to become first responder:
-(void)changeFirstResponder
{
[textField becomeFirstResponder]; // will return YES;
}
这篇关于如何将文本字段添加到inputAccessoryView并使textView作为第一响应者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!