[英]Swift/iOS: IBOutlet nil after loading view controller
我正在構建一個應用程序(在XCode 8.2.1中),其中一些對象顯示在2D板上,當用戶點擊其中一個對象時,應該將一些信息作為樣式模態信息框顯示出來。 我的設計是將信息寫在一個單獨的視圖控制器中,我會在需要時顯示。
我為第二個視圖控制器設計了一個基本存根,並在界面構建器中為它添加了一個標簽。 然后我將此標簽ctrl鏈接到我的自定義VC類:
class InfoViewController: UIViewController {
@IBOutlet weak var info: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func displayInfo() {
info.attributedText = NSAttributedString(string: "abc")
}
}
但是,當我測試我的應用程序並點擊該對象時,即使在我的自定義VC類的viewDidLoad()
方法中, info
字段也是nil
。 我正在顯示我的VC的方式如下:
let infoViewController = InfoViewController()
infoViewController.modalPresentationStyle = .overCurrentContext
self.present(infoViewController, animated: true, completion: nil)
infoViewController.displayInfo()
(注意:最后我將只有一個InfoViewController
實例,但這僅用於測試。我不希望全局實例會有任何區別嗎?)
正如我所說,無論是在viewDidLoad()
方法內還是在displayInfo()
方法中, info
始終為nil
,因此設置其attributedString
屬性會使應用程序崩潰。 思present
方法可以異步調用,我已經打過電話displayInfo()
從里面viewDidLoad()
但並沒有任何區別。
任何人都能告訴我我忘記了什么會讓我的IBOutlet
正確初始化嗎?
謝謝!
大衛
問題是對InfoViewController()
的引用,它獨立於任何故事板場景實例化視圖控制器。 您想使用instantiateViewController
:
let infoViewController = storyboard?.instantiateViewController(withIdentifier: "Info") as! InfoViewController
infoViewController.modalPresentationStyle = .overCurrentContext
present(infoViewController, animated: true) {
infoViewController.displayInfo()
}
幾個筆記:
這假定(a)你已經在故事板中給出了一個“故事板id”; (b)您已將該場景的基類設置為InfoViewController
。
請注意,我叫displayInfo
在完成處理器present
因為你可能不希望這樣叫,直到現場已被提出並網點已經迷上了。
或者,您可以在實例化后立即更新InfoViewController
非出口屬性,然后讓其viewDidLoad
獲取這些屬性並更新出口,例如:
class InfoViewController: UIViewController {
var info: String!
@IBOutlet weak var infoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
infoLabel.attributedText = NSAttributedString(string: info)
}
}
注意,我將@IBOutlet
名稱更改為infoLabel
並添加了名為info
的String
屬性。 這往往是慣例,出口帶有一些后綴表示控件的類型,而模型對象,如String
屬性,沒有后綴。 (您只需要確保在IB中的連接檢查器中刪除舊的插座,這樣您就不會遇到這些屬性名稱更改的問題。)
無論如何,你可以這樣做:
let infoViewController = storyboard?.instantiateViewController(withIdentifier: "Info") as! InfoViewController
infoViewController.info = "abc"
infoViewController.modalPresentationStyle = .overCurrentContext
present(infoViewController, animated: true, completion: nil)
關鍵點是在實例化之后不要嘗試立即更新場景的出口,但要確保在調用viewDidLoad
之前將其延遲。
我取代了
let vc = CCDetailViewController()
同
let vc = self.storyboard?.instantiateViewController(withIdentifier: "CCDetailViewController")
最后
self.present(vc!, animated: true, completion: nil)
現在它有效......
就我而言,我為同一個類創建了新的視圖控制器。 最后在故事板中有兩個視圖控制器,但指的是同一個類。 刪除舊視圖控制器后,一切正常。
希望對某人有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.