Tom Tom - 4 months ago 31
Swift Question

Setting a delegate when a specific tab is pressed

I have a delegate that I call logoSelectionDelegate. The delegate has one function to indicate if the user has changed their logo.

func userDidChangeLogo(image1: UIImage) {
pickedImage = image1
}


I used to set the delegate using the prepareForSegue function as below:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "SettingsIdentifier" {
let viewController:SelectALogoViewController = segue.destinationViewController as SelectALogoViewController
viewController.delegate=self

if pickedImage != nil {

viewController.pickedImage = pickedImage
}



}
}


This worked fine, however, now I have changed to a Tabbed application and I want to set the logoSelectionDelegate when the "settings" tab is pressed. Now I'm unsure how to do this, I was setting my TabBarController to be the logoSelectionDelegate, implementing my delegate function in the TabBarController.swift file and then using the didSelectViewController method to try and set the logoSelectionDelegate as below:

func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) -> Bool {

if (tabBarController.selectedIndex == 1) {

let viewController:SelectALogoViewController! = viewController as? SelectALogoViewController
viewController.delegate=self

if pickedImage != nil {

viewController.pickedImage = pickedImage
}

println("Yes")
}



return true



}


I can't get this to work and would welcome your comments / answers

Answer

You can access the tab bar's view controllers with this:

let viewController = self.tabBarController?.viewControllers?[1] as? SelectALogoViewController
    viewController?.delegate = self

Or the other option would be to call your methods directly and remove the delegate/protocol syntax altogether:

let viewController = self.tabBarController?.viewControllers?[1] as? SelectALogoViewController
    viewController?.doSomething()