如何将文本字段添加到inputAccessoryView,使TextView的第一个响应者
问题描述:
我的代码:如何将文本字段添加到inputAccessoryView,使TextView的第一个响应者
- (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]
,但它确实没有工作。
另一个委托方法在按下ENTER按钮时隐藏键盘的问题也不起作用。
- (BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
答
我正面临同样的挑战。由于UITextField
最初并未位于屏幕上,因此inputAccessoryView
中的文本字段拒绝成为第一响应者,因此您的(和我的初始)方法可能不起作用。
我的解决方案:检查键盘(以及附件视图)何时出现!
步骤1)侦听通知(确保在您想要接收通知之前执行此代码)。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(changeFirstResponder)
name:UIKeyboardDidShowNotification
object:nil];
步骤2)当键盘出现,可以设置文本框在inputAccessoryView
成为第一个响应者:
-(void)changeFirstResponder
{
[textField becomeFirstResponder]; // will return YES;
}
试试这个UIView的* AV = [[UIView的页头] initWithFrame:方法CGRectMake( 0.0,0.0,320.0,39.0)]; –
对不起,我没有提到它适用于iPad,并且此视图沿着键盘延伸,所以宽度没有意义。 – Michael