【问题标题】:How to add text field to inputAccessoryView and make the textView first responder如何将文本字段添加到 inputAccessoryView 并使 textView 成为第一响应者
【发布时间】:2011-11-12 04:04:39
【问题描述】:

我的代码:

- (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;
}

【问题讨论】:

  • 试试这个 UIView *av = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 39.0)];
  • 对不起,我没有提到它是用于 iPad 的,而且这个视图沿着键盘延伸,所以宽度没有意义。

标签: objective-c ios ipad uitextfield


【解决方案1】:

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

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

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

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

第 2 步)当键盘出现时,您可以将 inputAccessoryView 中的文本字段设置为第一响应者:

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

【讨论】:

  • 我正在尝试实现相同的目标,您的想法听起来可能可行,但是您如何让键盘首先出现?我有一个 UIButton 按下时我需要键盘在附件视图中显示一个文本字段。
  • @Darren 我知道一个半脏的解决方法,那就是在您的当前视图中已经有一个(隐藏的)文本字段并使用按钮操作来设置[yourHiddenTextField becomeFirstResponder]
  • 这正是我需要做的。谢谢
  • 当我在按下完成按钮后调用[textField resignFirstResponder]; 时,输入附件视图会向下滑动到屏幕底部并停留在那里。我需要手动将其从视图中删除吗?
  • Tom,我不确定使用 NSNotification 是否是个好主意。如果我在视图上有另一个文本字段并点击它,您的代码不会干扰我点击的其他文本字段吗?隐藏文本字段方法工作正常,我所做的只是添加隐藏文本字段,然后点击按钮,我调用我的方法使隐藏文本字段成为第一响应者,然后立即将 inputAccessoryView 文本字段设置为第一响应者。不需要任何 NSNotification 观察。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-26
  • 2020-08-24
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-05
相关资源
最近更新 更多