Set UINavigationBar appearance whenContainedInInstancesOf to my viewcontroller not working

10k Views Asked by At

I want to set white barTintColor in some viewcontroller I have set UINavigationBar.appearance().barTintColor for all default color but when I use appearance whenContainedInInstancesOf It's not change my viewcontroller

UINavigationBar.appearance(whenContainedInInstancesOf: [MyViewController.self]).barTintColor = .white

Any idea?. I tried this in my viewcontroller

self.navigationcontroller.navigationbar.barTintColor = .white

but I have to set color back to default when screen will disappear. I don't want to do like that. How can I do?

4

There are 4 best solutions below

6
zombie On

UINavigationBar is contained in a UINavigationController not UIViewController

with that said you need to create a custom UINavigationController

an empty class will do the job

class NavigationController: UINavigationController {}

then we can use it

UINavigationBar.appearance(whenContainedInInstancesOf: [NavigationController.self]).barTintColor = .white

Example can be found here

0
ArtSabintsev On

@zombie has the correct answer. I just came across this issue a moment ago with UISearchBar. Here's the Swift 3 version of the answer. Using .red as the sample UIColor for this example.

 let textField = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
 textField.tintColor = .red

 let searchBar = UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self])
 searchBar.setTitleTextAttributes([NSForegroundColorAttributeName: .red], for: .normal)
 searchBar.setTitleTextAttributes([NSForegroundColorAttributeName: .red], for: .disabled)

Sample Image

0
Steve Moser On

Swift 4:

    // For the cursor color
    let textField = UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self])
    textField.tintColor = .lightBlue

    // For the cancel button on search bar
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .normal)
    UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.lightText], for: .disabled)
0
khush On
UIBarButtonItem.appearance(whenContainedInInstancesOf: [UIImagePickerController.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)

This worked for me!