2015-06-01 64 views
0

我正在切換tabBar以編程方式 - 哪些工作正常。然而,一個IBOutlet mapView(谷歌地圖)變成零 - 導致崩潰...以編程方式切換tabBar導致IBOutlet爲零

我已經花了不少幾個小時。感覺像我缺少一些微不足道的東西。通過SO看,例如: Switch tab bar programatically in SwiftAll my IBOutlet are nil in viewDidLoad但沒有運氣。

任何幫助非常感謝!

應用程序委託

func goToTabRoot(){ 
    if let tabBarController = self.window!.rootViewController as? UITabBarController { 
     let index = 0 // First (root) tab 
     tabBarController.selectedIndex = index 
     let vc = tabBarController.viewControllers![index] as! UINavigationController 
     tabBarController.delegate?.tabBarController!(tabBarController, didSelectViewController:vc) 
    } 
} 

地圖視圖控制器

class MapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate, BudgetTableViewControllerDelegate, StoreViewControllerDelegate, ProductPickedViewControllerDelegate { 

@IBOutlet weak var mapView: GMSMapView! 

override func viewDidAppear(animated: Bool) { 
    locationManager.delegate = self 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest // Best accuracy 
    locationManager.requestWhenInUseAuthorization() 
    mapView.delegate = self // <== ERROR HERE. mapView = nil 

    println("ViewDidAppear called") 
} 


func favoriteViewDidFinish(controller: MapViewController, productIds: [Product]) { 
    println("Favorite finished") 

    // Select MapView 
    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 
    appDelegate.goToTabRoot() 

    // Store product IDs 
    self.productIds = productIds 

    // Update stores (download) 
    queryType = "filterProducts" 
    downloadStores = true 
    updateStores() 

} 

產品選擇

protocol ProductPickedViewControllerDelegate: class { 
    func favoriteViewDidFinish(controller: MapViewController, productIds: [Product]) 
} 

class ProductPickedViewController: UIViewController, UITabBarControllerDelegate { 

var delegate:ProductPickedViewControllerDelegate? = nil 

@IBAction func storesButtonPressed(sender: AnyObject) { 

    // Set delegate 
    delegate = MapViewController() // First view controller 

    // Download relevant stores 
    println("Should reload stores...") 
    if (self.delegate != nil) { 
     println("activate delegate") 
     self.delegate!.favoriteViewDidFinish(MapViewController(), productIds: productsPresented) 
    } 

回答

1

問題是當您使用下面的行設置委託時,您正在創建MapViewController的新實例。該實例不是在故事板中製作的,因此它對您的IBOutlet一無所知。

delegate = MapViewController() 

您需要獲取對已存在的控制器的引用。如果ProductPickedViewController是在標籤欄控制器的視圖控制器之一,你可以這樣做的話,

delegate = self.tabBarController!.viewControllers[0] as! MapViewController 
+0

謝謝@rdelmar - 讓有很大的意義。不過,我現在得到錯誤「無法將類型'MapViewController'的值分配給類型爲'ProductPickedViewControllerDelegate?'的值」。要確認 - ProductPickedViewController是標籤欄控制器上的一個VC。任何想法如何補救? –

+0

通過迫使downcast:'self.tabBarController!.viewControllers![0] .viewControllers [0] as! MapViewController'。 TabBar中的第一個VC嵌入在NavBar中。再次感謝!讓我的一天! –