[英]Can't call ViewController method from AppDelegate
在AppDelagate中,我在方法中調用以下內容
func example() {
ViewController().test()
}
在我的ViewController中,方法是
func test() {
testView.userInteractionEnabled = true
buttonTapped(UIButton())
restartTimer()
}
但由於testView出現nil錯誤,因此每次調用該方法時都會崩潰。 testView是ViewController中的視圖,而不是AppDelegate中的視圖,但是我不知道如何制作它,因此該方法的執行方式就像我在ViewController中調用它的方式一樣。
IBOutlet
nil
直到視圖控制器調用viewDidLoad
為止。 由於您嘗試直接通過調用ViewController()
實例化該類,因此未發生viewDidLoad
。
因此,正如預期的那樣, testView
為零。 無論如何,您的AppDelegate
不應對ViewController
邏輯負責。
您可能現在知道,由於正在訪問IBOutlet
才有機會對其進行初始化,因此您的崩潰正在發生。 因此,我猜想testView
的聲明像這樣:
@IBOutlet weak var testView: UIView!
解決方案A
您可以將其設為可選,以避免此崩潰:
@IBOutlet weak var testView: UIView?
並將VC中的語法更改為:
testView?.userInteractionEnabled = true
解決方案B
如果此時確實需要關閉用戶交互,則可以強制加載視圖:
let myVc = ViewController()
_ = myVc.view // this will force the myVc.view to be loaded
myVc.test()
這樣,您的IBOutlet
就有機會在運行test()
方法之前進行初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.