【问题标题】:iOS Swift: Move focus from one textfield to anotheriOS Swift:将焦点从一个文本字段移动到另一个
【发布时间】:2015-09-30 23:05:11
【问题描述】:

我正在开发一个 iOS 应用程序,它使用 PageViewController 来包装几个“聊天室”。我在每个页面中都有一个 TextField,当我滑动以移动到另一个页面时,我想将焦点从当前页面 TextField 更改为新页面 TextField 而不会丢失键盘。

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

你能帮帮我吗?

谢谢!

【问题讨论】:

  • 您是否在旧文本字段中调用resignFirstResponder?如果是,请不要。
  • 没有。我根本没有使用 resignFirstResponder

标签: ios swift textfield becomefirstresponder


【解决方案1】:

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

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

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
}

我让我的应用根据需要运行。

【讨论】:

    【解决方案2】:

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

    我刚刚在一个新项目中测试了这个(使用“基于页面的应用程序”模板),它工作正常。

    【讨论】:

    • 感谢您的 awnser jrc。这是一个有效的解决方案,但是我需要在每个子页面中都有一个文本字段,因为我不想在更改到另一个页面时丢失在文本字段中输入的文本(我也可以将文本保存在子页面变量中,但是我发现我目前的解决方案没问题)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多