【问题标题】:Swift. After addSubview click listeners dont work迅速。 addSubview 点击监听器后不起作用
【发布时间】:2021-04-24 17:17:52
【问题描述】:

我有一个 testVC。 TestVC 没有情节提要,这个 viewController 有 XIB 文件。当我没有互联网时,我会展示这个 VC。以及像这样展示这个 VC 的逻辑:

 let getVC = NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil)
        if let getWindow = self.window {
            getVC.view.tag = 501
            getVC.view.frame = getWindow.bounds
            getWindow.addSubview(getVC.view)
        }

我也有 UIViewController 的扩展

extension UIViewController {
     var appDelegate: AppDelegate {
     return UIApplication.shared.delegate as! AppDelegate
 }
 
 var sceneDelegate: SceneDelegate? {
     guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
         let delegate = windowScene.delegate as? SceneDelegate else { return nil }
      return delegate
 }
}

extension UIViewController {
 var window: UIWindow? {
     if #available(iOS 13, *) {
         guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
             let delegate = windowScene.delegate as? SceneDelegate, let window = delegate.window else { return nil }
                return window
     }
     
     guard let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window else { return nil }
     return window
 }
}

如果我像这样显示此视图控制器,TestVC 中的所有点击都有效:

navController.pushViewController(NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil), animated: true)

但它不适合我。我需要像我上面描述的那样显示NoInternetConnectionVC,也就是像这样。当我在下面显示 NoInternetConnectionVC 时,我的所有听众都停止工作

 let getVC = NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil)
            if let getWindow = self.window {
                getVC.view.tag = 501
                getVC.view.frame = getWindow.bounds
                getWindow.addSubview(getVC.view)
            }

我尝试将行 isUserInteractionEnabled 添加到我的代码中,像这样

if let getWindow = self.window {
            getVC.view.tag = 501
            getVC.view.isUserInteractionEnabled = true //added line
            getVC.view.frame = getWindow.bounds
            getWindow.addSubview(getVC.view)
        }

但它不起作用

【问题讨论】:

  • 添加子视图后试试这个:let root = UIApplication.shared.windows.first?.rootViewController root?.addChild(getVC) getVC.didMove(toParent: root!)
  • 试试这个let getVC = Bundle.main.loadNibNamed("NoInternetConnectionView", owner: self, options: nil)?.first as? NoInternetConnectionVC 而不是let getVC = NoInternetConnectionVC(nibName: "NoInternetConnectionView", bundle: nil)
  • @RajaKishan 太神奇了!它的作品,谢谢!你可以像回答一样添加这个,我接受它

标签: ios swift


【解决方案1】:

您刚刚将其添加为子视图。添加子视图后,将控制器移至父级。

if let root = UIApplication.shared.windows.first?.rootViewController {
    root.addChild(getVC)
    getVC.didMove(toParent: root)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    相关资源
    最近更新 更多