Search code examples
swiftsegueuibarbuttonitemtintcolor

How can I change tint color of a button via prepareForSegue


I have two viewControllers that have segues to the same mapViewController. So I tried to change the tint color of a toolbar button on the map but of course it said error nil. Is there another way to do this. Because I need to tell the compiler that if the segue is coming from the tableViewController then make the bar button white "As if not selected" and if the segue was sent from the mainViewController then make the bar button yellow.

This is the tableView code

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "locationView"{

        let mapVC:MapViewController = segue.destinationViewController as! MapViewController
        mapVC.pinCoordinate = coordinate
        mapVC.snippetTitle = caseTitleOnLocation
        mapVC.snippetDescription = caseDescriptionOnLocation
        mapVC.addLocation.tintColor = UIColor.whiteColor()  //error

This is the mainViewController code

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if segue.identifier == "rescueMap"{
        let mapVC:MapViewController = segue.destinationViewController as! MapViewController
        mapVC.addLocation.tintColor = UIColor.yellowColor()  //error
    }

Solution

  • The reason why you have an error is because you are trying to set a value on a view that doesn't exist YET.

    You can create a UIColor() variable in mapViewController then pass the color you want

    Ex.

    In mapViewController

    class mapViewController{
    
       var barColor : UIColor!
    
       override func viewDidLoad(){
         self.toolbar.barTintColor = barColor
       }
    }
    

    In mainViewController

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    
        if segue.identifier == "rescueMap"{
            let mapVC:MapViewController = segue.destinationViewController as! MapViewController
            mapVC.barColor = UIColor.yellowColor() 
        }
    

    you'll get the idea.