Search code examples
iosswiftuinavigationitem

The NavigationItem's TintColor can not be set


My Situation:

  • There are a View_A (UICollectionViewController&UICollectionViewCell) and View_B (UIViewController). I want to switch to the View_B when I touched one of cell in the View_A with Segue in the StoryBoard.

  • In the StoryBoard, I connected View_A and View_B with the Push Segue which identifier is SegueToView_B.

  • And the function of switchViews just worked fine.

My Problem:

  • With the Push Segue, I do not need to add a BackButton (NavigationItem) to turn back to the View_A, because there is a 'NavigationItem' be crated automatically by system. And I tried other type segues, like Modal, Popover, and the NavigationItem was not created automatically. I want to ask why?

  • I want to set the specific color, not the default blue, for that NavigationItem which be created by system automatically, but I failed to find it. After that I just set the color in the prepareForSegue(), but it did not work. Please tell how to set the specific color for it?

My Code:

 override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    self.collectionView?.setPresenting(true, animated: true, completion: nil)
    let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
    self.selectedCard = delegate.otherCards[indexPath.row]
    self.performSegueWithIdentifier("SegueToView_B", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if let identifier = segue.identifier {
        if identifier == "SegueToView_B" {
            let myOtherCardViewController = segue.destinationViewController as? View_BViewController
            myOtherCardViewController!.otherCard = self.selectedCard
            myOtherCardViewController!.navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()  // Failed to work!!!
            myOtherCardViewController?.navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()  // Failed to work, too!!!
        }
    }
}

Thanks for your help.

Ethan Joe


Solution

  • To set the tintColor for that navigation bar:

    myOtherCardViewController.navigationBar.tintColor = .whiteColor()
    

    Why there is no Navigationbar when you use the Modal or PopOver? Because thats how Modal and Popover work! You have to create another Navigation controller for the view you are connecting with the Modal segue, like this: enter image description here

    Another technique I am using is, to create a single NavigationController class, and set all the desired properties (color, font etc.) and then link all the NavigationControllers in the Storyboard to that NavigationController class.

    With that you wont have to reconfigure every NavigationController.