【问题标题】:Swift add view to front via appdelegateSwift 通过 appdelegate 将视图添加到前面
【发布时间】:2018-01-30 18:47:54
【问题描述】:

尝试通过 AppDelegate 将子视图添加到 UI 的前面,但它不起作用。我有一个可达性通知器,当没有互联网连接时,它应该从 xib 添加 UIView。

应用代理代码:

func reachabilityChanged(note: Notification) {
    let reachability = note.object as! Reachability
    if !reachability.isReachable {
        print("APP: Network reachable")
        if networkErrorView != nil {
            networkErrorView.removeFromSuperview()
        }
    } else {
        print("ERROR: Network not reachable")
        networkErrorView = NetworkErrorView(frame: CGRect(x: 30, y: self.window!.frame.height / 4, width: self.window!.frame.width - 60, height: self.window!.frame.height / 2))
        UIApplication.shared.keyWindow?.addSubview(networkErrorView)
        UIApplication.shared.keyWindow?.bringSubview(toFront: networkErrorView)
        print("View is showing")
    }
}

通知确实触发了,并且我确实将“视图正在显示”打印到控制台。我尝试通过dispatchQueue.main.async 调用它,但这只会导致应用程序崩溃的无限循环。

谢谢

【问题讨论】:

    标签: ios swift reachability


    【解决方案1】:
    private func dismissOfflineScreen() {
        if let navigationVC = self.window?.rootViewController?.presentedViewController as? UINavigationController, navigationVC.viewControllers.first is OfflineViewController {
            navigationVC.dismiss(animated: true, completion: nil)
        }
    }
    
    private func presentOfflineScreen() {
        let navigationVC = UINavigationController(rootViewController: OfflineViewController())
        navigationVC.view.backgroundColor = UIColor.clear
        navigationVC.modalPresentationStyle = UIModalPresentationStyle.overFullScreen
        self.window?.rootViewController?.present(navigationVC, animated: true)
    }
    

    【讨论】:

    • 视图控制器会是比添加视图、易于控制等更好的解决方案吗?
    【解决方案2】:

    在 else 中尝试访问当前的 viewController :

    if let currentViewController = self.window?.rootViewController {
        let screenSize = UIScreen.main.bounds
        networkErrorView = NetworkErrorView(frame: CGRect(x: 30, y: (screenSize.height / 4), width: (screenSize.width - 60), height: (screenSize.height / 2)))
        currentViewController.view.addSubview(networkErrorView)
        currentViewController.view.bringSubview(toFront: networkErrorView)
    }
    

    【讨论】:

    • 尝试了这种方法并遇到了同样的问题。
    • @user1888564 是您的评论:打印(“视图正在显示”)在日志中仍然可见吗?我已经用 UIScreen.main.bounds 编辑了 UIView 的大小。
    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多