如何将文本字段添加到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; 
} 
+0

试试这个UIView的* AV = [[UIView的页头] initWithFrame:方法CGRectMake( 0.0,0.0,320.0,39.0)]; –

+0

对不起,我没有提到它适用于iPad,并且此视图沿着键盘延伸,所以宽度没有意义。 – Michael

我正面临同样的挑战。由于UITextField最初并未位于屏幕上,因此inputAccessoryView中的文本字段拒绝成为第一响应者,因此您的(和我的初始)方法可能不起作用。

我的解决方案:检查键盘(以及附件视图)何时出现!

步骤1)侦听通知(确保在您想要接收通知之前执行此代码)。

[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(changeFirstResponder) 
              name:UIKeyboardDidShowNotification 
              object:nil]; 

步骤2)当键盘出现,可以设置文本框在inputAccessoryView成为第一个响应者:

-(void)changeFirstResponder 
{ 
    [textField becomeFirstResponder]; // will return YES; 
} 
+0

我试图达到同样的效果,你的想法听起来像可能会奏效,但是你如何让键盘出现在第一位呢? 我有一个UIButton按下时,我需要键盘才能在附件视图中显示文本字段。 – Darren

+0

@Darren我知道一个半脏解决方法,那就是已经在当前视图中有一个(隐藏的)文本框,并使用按钮操作来设置'[yourHiddenTextField becomeFirstResponder]' – Tom

+0

这正是我需要做的。 Thx – Darren