2016-12-21 140 views
-2

我試圖通過函數func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)將數據傳遞給我的第二個VC上的標籤。Swift:Constant''在被初始化之前使用

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) { 

    print("Annotation selected") 


    if let annotation = view.annotation as? POIAnnotations { 

     let destVC : ShopDetailViewController 

     destVC.shopName.text = annotation.title! 

     print("Your annotation title is: \(annotation.title!)") 

    } 

} 

當我設置shopName.textannotation.title,我得到一個錯誤,指出:正在初始化之前使用

常量 'destVC'。

我不太確定發生了什麼問題。

回答

5

你只是聲明的變量destVC,沒有初始化它。您需要在變量使用前直接或通過故事板來實例化變量,例如這樣的:

let destVC = ShopDetailViewController() 

let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil) 
let destVC = storyboard.instantiateViewController(withIdentifier: "ShopDetailViewController") as! ShopDetailViewController 
2

錯誤很明顯,表示您尚未初始化常量destVC,並嘗試使用其屬性shopName。所以在訪問其屬性之前初始化destVC將刪除錯誤。

如果您正在使用storyboard

let destVC = self.storyboard?.instantiateViewController(withIdentifier: "IdentifierOfVC") as! ShopDetailViewController 

如果您正在使用xib

let destVC = ShopDetailViewController() 
+0

不會'讓destVC:ShopDetailViewController'是初始化呢?我還會如何初始化它? – daanyyaal

+0

@daanyyaal如果你不知道如何在故事板中設置viewController的標識符檢查這個答案http://stackoverflow.com/a/15478575/6433023 –

相關問題