【问题标题】:Simulate Tab Key Press in iOS SDK在 iOS SDK 中模拟 Tab 键按下
【发布时间】:2011-04-26 01:59:49
【问题描述】:

当硬件键盘与 iOS 一起使用时,按 tab 或 shift-tab 会分别自动导航到下一个或上一个逻辑响应程序。有没有办法以编程方式执行相同的操作(即模拟 Tab 键而不是手动跟踪逻辑顺序)?

【问题讨论】:

标签: iphone keyboard ios4


【解决方案1】:

William Niu 是对的,但您也可以使用下面解释的这段代码。

我已经使用了这个并且成功了。现在考虑UITextField的例子......

您可以使用 UITextView 的委托方法-(BOOL)textFieldShouldReturn:(UITextField*)textField,如下所述。

但在这样做之前,您应该必须以递增顺序为每个 UITextField 赋予标签...(递增顺序不是必需的,但至于我的代码它是必需的,您也可以使用递减顺序但一些代码更改这样做)

- (BOOL)textFieldShouldReturn:(UITextField *)textField {

    NSInteger nextTag = textField.tag + 1;
    UIResponder* nextResponder = [self.view viewWithTag:nextTag];   
    if (nextResponder) {
        [nextResponder becomeFirstResponder];       
    } else {
        [textField resignFirstResponder];
    }
    return YES;
}

希望这对你有用...

编码愉快....

【讨论】:

  • 这适用于静态文本字段,实际上是一个很好的方法,但如果您的文本字段位于可重复使用的 tableviewcells 中,这一切都会变得疯狂。
【解决方案2】:

您可以使用标签属性定义“标签顺序”。下面的文章描述了如何为UITextFields 找到下一个标签索引, How to navigate through textfields (Next / Done Buttons)

这是该帖子中代码的修改版本。下面的代码不会在最后一个标签索引处删除键盘,而是尝试循环回第一个标签索引。

-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
  NSInteger nextTag = textField.tag + 1;
  // Try to find next responder
  UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
  if (nextResponder) {
    // Found next responder, so set it.
    [nextResponder becomeFirstResponder];

    return NO;
  }

  // Try to find the first responder instead...
  // Assuming the first tag index is 1
  UIResponder* firstResponder = [textField.superview viewWithTag:1];
  if (firstResponder) {
    // loop back to the first responder
    [firstResponder becomeFirstResponder];
  } else {
    // Not found, so remove keyboard.
    [textField resignFirstResponder];
  }

  return NO; // We do not want UITextField to insert line-breaks.
}

如果您想要 UITextField 以外的 UI 元素,您应该仍然可以使用相同的逻辑,但需要进行更多检查。

【讨论】:

    【解决方案3】:

    不确定这是否有帮助,但在 UITextFields 的上下文中,如果您实现 UITextFieldDelegate,则按下软键盘的返回键时将调用 - (BOOL)textFieldShouldReturn:(UITextField *)textField

    我尝试直接在我的笔记本电脑键盘上敲击,它似乎按照您将它们添加到视图中的顺序在所有文本字段之间跳转,但没有转到任何其他类型的字段(按钮等等)。

    键盘上的键是模拟模拟器软键盘上的键,按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 2018-08-14
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 2010-10-16
      • 1970-01-01
      相关资源
      最近更新 更多