【问题标题】:KEEP keyboard ON when UIAlertcontroller is presented in Swift?Swift 中显示 UIAlertcontroller 时保持键盘打开?
【发布时间】:2015-04-18 08:07:09
【问题描述】:

当警报弹出时,键盘被关闭。我到处寻找,但没有找到保持键盘可见的解决方案。当警报出现时,文本字段似乎会自动退出第一响应者,因为警报以模态方式出现。如何将键盘保持在此警报后面,这意味着即使无法进行交互,文本字段仍在编辑?

【问题讨论】:

    标签: ios swift keyboard uialertcontroller presentviewcontroller


    【解决方案1】:

    这个解决方案对我有用:

    let rootViewController: UIViewController = 
        UIApplication.sharedApplication().windows.lastObject.rootViewController!!
    rootViewController.presentViewController(alert, animated: true, completion: nil)
    

    @galambalazs 编辑: 它起作用的原因是:

    您可以抓取当前最高窗口级别的窗口,并将您的 View Controller 显示在该 Window 中(使其成为顶部 View Controller在顶部窗口)。

    UIApplication.sharedApplication().windows
    数组中的窗口按窗口级别从后到前排序;
    因此,数组中的最后一个窗口位于所有其他应用程序窗口的顶部。

    您可能还需要设置该窗口的 tintColor,使其与您的应用程序全局 tintColor 匹配。

    UIWindow *topWindow = [UIApplication sharedApplication].windows.lastObject;
    // we inherit the main window's tintColor because topWindow may not have the same
    topWindow.tintColor = [UIApplication sharedApplication].delegate.window.tintColor;
    

    【讨论】:

    • 看起来这是在使用状态栏所在的窗口来呈现警报控制器,对吧?
    • 其实我错了。 UIAppplication.sharedApplication().windows 中的第二个窗口是 UITextEffectsWindow。
    • 经过更多研究,我发现UITextEffectsWindow是键盘视图(或UIViewController inputAccessoryView)所在的位置。所以这个第二个窗口只有在键盘被显示的情况下才会存在。 fantageek.com/1317/uiwindow-in-ios
    • 所以这对我有用。虽然背景变黑了,如果您使用效果作为背景(使用实际视图控制器的视图),这并不好。过渡也不好(因为用黑色背景替换了实际视图)。仍在寻找更好的解决方案...
    • 我认为你应该使用 UIApplication.sharedApplication().windows.lastObject.rootViewController,然后代码无论键盘显示还是隐藏都可以工作。
    【解决方案2】:

    适用于 Swift 3 和 iOS11

    if let alertWindow = UIApplication.shared.windows.last, alertWindow.windowLevel == 10000001.0 // If keyboard is open
      { // Make sure keyboard is open
        alertWindow.rootViewController?.present(alertController, animated: true, completion: nil)
      }
      else
      {
        viewController?.present(alertController, animated: true, completion: nil)
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2015-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多