ios - 无法从 AppDelegate 调用 ViewController 方法

标签 ios swift uiviewcontroller appdelegate

在 AppDelagate 中,我在一个方法中调用了以下内容

func example() {
    ViewController().test()
}

在我的 ViewController 中,方法是

func test() {
    testView.userInteractionEnabled = true
    buttonTapped(UIButton())
    restartTimer()
}

但由于 testView 的 nil 错误,每当我调用该方法时它都会崩溃。 testView 是 ViewController 中的 View ,而不是 AppDelegate 中的 View ,但我不知道如何制作它,所以该方法的执行方式与我在 ViewController 中调用它时的方式相同。

最佳答案

在 View Controller 调用 viewDidLoad 之前,IBOutletnilviewDidLoad 没有发生,因为您试图通过调用 ViewController() 直接实例化该类。

因此,testView 正如预期的那样为零。无论如何,您的 AppDelegate 不应该对 ViewController 逻辑负责。

关于ios - 无法从 AppDelegate 调用 ViewController 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30181123/

相关文章:

ios - UISegmentedControl 在解散后更改色调颜色

Swift 枚举,将值设置为项目的名称?

ios - 改变UIView的高度

uiview - iOS 应用程序 UI 的层次结构

ios - ViewController 不访问您的元素

ios - 使用 3D touch peek and pop,您如何检测用户在 peek 期间的平移(如 Facebook)?

ios - 编译 Swift 时收到 “Include of non-modular header inside framework module”

ios - 如何在 swift 中同时为相机和照片库制作 UIImagePickerController

iphone - 如何限制 UILabel 文本长度 - IOS

ios - 使用 lldb 呈现 ViewController