如何浏览文本字段(下一步/完成按钮) [英] How to navigate through textfields (Next / Done Buttons)

查看:35
本文介绍了如何浏览文本字段(下一步/完成按钮)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 iPhone 键盘上的下一步"按钮浏览所有文本字段?

How can I navigate through all my text fields with the "Next" Button on the iPhone Keyboard?

最后一个文本字段应该关闭键盘.

The last text field should close the Keyboard.

我已经设置了 IB 按钮(下一步/完成),但现在我卡住了.

I've setup the IB the Buttons (Next / Done) but now I'm stuck.

我实现了 textFieldShouldReturn 操作,但现在 Next 和 Done 按钮关闭了键盘.

I implemented the textFieldShouldReturn action but now the Next and Done Buttons close the Keyboard.

推荐答案

在 Mac OS X 的 Cocoa 中,您有下一个响应者链,您可以在其中询问文本字段接下来应该关注哪个控件.这就是使文本字段之间的 Tab 能够工作的原因.但由于 iOS 设备没有键盘,只有触摸,这个概念在向 Cocoa Touch 过渡后没有幸存下来.

In Cocoa for Mac OS X, you have the next responder chain, where you can ask the text field what control should have focus next. This is what makes tabbing between text fields work. But since iOS devices do not have a keyboard, only touch, this concept has not survived the transition to Cocoa Touch.

无论如何,这很容易做到,有两个假设:

This can be easily done anyway, with two assumptions:

  1. 所有可选项卡"UITextField 都在同一个父视图上.
  2. 它们的tab-order"由标签属性定义.
  1. All "tabbable" UITextFields are on the same parent view.
  2. Their "tab-order" is defined by the tag property.

假设您可以重写 textFieldShouldReturn: 如下:

Assuming this you can override textFieldShouldReturn: as this:

-(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];
  } else {
    // Not found, so remove keyboard.
    [textField resignFirstResponder];
  }
  return NO; // We do not want UITextField to insert line-breaks.
}

再添加一些代码,假设也可以忽略.

Add some more code, and the assumptions can be ignored as well.

Swift 4.0

 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    let nextTag = textField.tag + 1
    // Try to find next responder
    let nextResponder = textField.superview?.viewWithTag(nextTag) as UIResponder!

    if nextResponder != nil {
        // Found next responder, so set it
        nextResponder?.becomeFirstResponder()
    } else {
        // Not found, so remove keyboard
        textField.resignFirstResponder()
    }

    return false
}

如果文本字段的超级视图将是 UITableViewCell 那么下一个响应者将是

let nextResponder = textField.superview?.superview?.superview?.viewWithTag(nextTag) as UIResponder!

这篇关于如何浏览文本字段(下一步/完成按钮)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆