iOS Swift: 将焦点从一个文本字段移动到另一个文本字段

iOS Swift: Move focus from one textfield to another

我正在开发一个 iOS 应用程序,它使用一个 PageViewController 来包装多个 "Chat rooms"。我在每个页面中都有一个 TextField,当我滑动以移动到另一个页面时,我想在不丢失键盘的情况下将焦点从当前页面 TextField 更改到新页面 TextField。

我尝试了不同的方法,但我做不到,每次我在新页面 TextField 中调用 becomeFirstResponder 时,键盘会下降,然后立即上升,然后文本字段成为第一响应者。

你能帮帮我吗?

谢谢!

我找到了这个问题的解决方案:

在每个页面中使用一个变量

var firstResponderIsLocked: Bool = false

检查 TextField 是否应该结束编辑

func textFieldShouldEndEditing(textField: UITextField) -> Bool {
    return !firstResponderIsLocked
}

当我在页面之间滑动时处理它:

func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) {
    if let viewControllerToShow = pendingViewControllers[0] as? LiveMessagingPageContentViewController {
        pendingViewControllerIndex = viewControllerToShow.index
        lockFirstResponder(pendingViewControllerIndex!)
    }
}

func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if completed && pendingViewControllerIndex != nil {
        takeFirstResponder(pendingViewControllerIndex!)
    }
    pendingViewControllerIndex = nil
}

我让我的应用程序按需工作。

将文本字段放在页面视图控制器的视图上,而不是每个子页面上。在页面视图控制器中,调用 self.view.bringSubviewToFront(textField) 将其置于顶部。

我刚刚在一个新项目中测试了这个(使用 "Page-Based Application" 模板)并且它工作正常。