首页 > 解决方案 > 如何将布尔值从应用程序委托传输到视图控制器?

问题描述

我目前正在尝试将变量从应用程序委托传输到 ViewController。我找到的大多数指南都在 Objective-c 中,我没有将代码转换为 swift 的技能。有人可以帮我找到一种方法来做到这一点。

func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        var isIpad: Bool!
        if UIDevice.current.userInterfaceIdiom == .pad {
            isIpad = true
            print("iPad")

        }else{
            print("not iPad")
            isIpad = false
        }

    }

标签: swiftappdelegate

解决方案


虽然我建议看一下@rmaddy 的第一条评论,但您可以在模块中的任何位置声明一个存储属性(不必在应用程序委托中声明):

let isIpad = UIDevice.current.userInterfaceIdiom == .pad

这意味着不需要将值从应用程序委托传递给视图控制器。因此在视图控制器中——例如——:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if isIpad {
            // ...
        }
    }
}

推荐阅读