以编程方式切换tabBar会导致IBOutlet为零

时间:2015-06-01 15:10:17

标签: ios swift delegates uitabbarcontroller iboutlet

我正在以编程方式切换tabBar - 工作正常。但是,IBOutlet mapView(谷歌地图)变为零 - 导致崩溃......

我已经花了好几个小时。感觉就像我错过了一些微不足道的东西。看看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 个答案:

答案 0 :(得分:1)

问题是,当您使用以下行设置委托时,您正在创建<input type="text" ng-model="data.id">的新实例。该实例未在故事板中制作,因此它对您的MapViewController一无所知。

IBOutlet

您需要获取已存在的控制器的引用。如果delegate = MapViewController() 是标签栏控制器中的一个视图控制器,则可以这样做,

ProductPickedViewController