[英]Storyboard button not known in viewDidLoad
我有一個帶按鈕的main.storyboard,我需要根據應用程序通過家庭Wifi網絡或通過雲連接到特定設備的方式來更改圖像。 我給按鈕加了標簽號。
在viewDidLoad中,我檢查連接並根據需要更改圖像。 我通過
let myButton = view.viewWithTag(int) as! UIButton
myButton.setImage(UIImage(named: “imageName.png”), for .normal)
我的viedDidLoad看起來像這樣
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(setHomeMenuButton), name:NSNotification.Name(rawValue: "refresh"), object: nil)
checkSavedHomeyAccessData() // get Homey's url data from disk if there are
if appStageLevel > 0 && firstStartAppFlag {
firstStartAppFlag = false
let flag = checkDataStore()
if flag == 2 { // store is already filled, then get iconViews
DeviceService.getDevicesNameArray()
getIconFiles()
}
}
manageViewBasedAppStageLevel() // setup views based on stage
let networkName = currentSSID()
timerMapCapabilitiesUpdate()
}
直到今天,它的功能都很好。 我在viewDidLoad函數中添加了一個新函數調用,該應用程序在啟動后立即崩潰,並告訴我帶有'let myButton = ...'的行意外地找到nill。
這是現在從viewDidLoad調用的函數:
func timerMapCapabilitiesUpdate() {
let mapCapabilityArray = getMapCapabilityArray()
_ = Timer.scheduledTimer(withTimeInterval: 20, repeats: true, block: { (timer) in // 1
if self.currentReachabilityStatus != .notReachable {
if mapCapabilityArray.count != 0 {
for capabilityOnMap in mapCapabilityArray {
getLiveData2Values(tag : capabilityOnMap.tag)
} // for deviceOnMap
} // if mapDeviceArray
} else {
if let viewWithTag = self.view.viewWithTag(6) {
viewWithTag.isHidden = false
self.view.bringSubview(toFront: viewWithTag)
// print("No Internet Connection")
}
} // if internet available
}) // end timer block
} // end timerMapDevicesUpdate
以我的拙見,這意味着故事板在viewDidLoad方法啟動之前尚未加載。 因為如果加載了情節提要板,則展開將不會產生“零”。 有人知道如何解決這個問題嗎?
在viewDidLoad
期間,大多數UI元素仍為nil
。 如果將調用移至viewWillAppear
或viewDidAppear
您將發現元素已初始化,可以修改myButton
對象。
因為viewWillAppear
和viewDidAppear
可以被調用多次,所以您可能需要稍微改變一下邏輯。
我快速瀏覽了一下“ UIViewController生命周期”的Google文章,並找到了一些博客文章,它們詳細介紹了如果您想了解更多信息,那么每個標准步驟會發生什么。 蘋果曾經有過這樣的文章,但我今天找不到。 但是, UIViewController文檔的“響應視圖事件”和“處理視圖相關通知”部分也將為您提供基礎知識。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.