user5483739
user5483739

Reputation:

How to change tintColor of UIBarButtonItem in Swift?

I want to change the color of my right bar button item from black to white. It is a button as a search icon. I have not coded the search implementation yet as I want to get the main interface completed first. I thought that I'd written the correct codes so it should appear as white, but it seems to still appear as black in both the storyboard and simulator.

In the storyboard, I have also set it to white.

Here is my code, which is located in the AppDelegate.swift file:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    // Changing the status bar's colour to white
    UIApplication.sharedApplication().statusBarStyle = .LightContent

    // Changing the navigation controller's background colour
    UINavigationBar.appearance().barTintColor = UIColor(red: 0.0/255.0, green: 165.0/255.0, blue: 227.0/255.0, alpha: 1.0)

    // Changing the navigation controller's title colour
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]

    // Changing the colour of the bar button items
    UINavigationBar.appearance().tintColor = UIColor.whiteColor()

    // Changing the tint colour of the tab bar icons
    UITabBar.appearance().tintColor = UIColor(red: 0.0/255/0, green: 165.0/255.0, blue: 227.0/255.0, alpha: 1.0)

    return true
}

Here is an image of the simulator:

enter image description here

I find it odd that this line of code doesn't work. Any solution?

Upvotes: 9

Views: 15017

Answers (3)

Shubham Mishra
Shubham Mishra

Reputation: 1331

Setting Text Color For Normal Text:

let uiBarButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logOutTapped))
uiBarButton.tintColor = UIColor.appColor
navigationItem.rightBarButtonItems = [uiBarButton]

Setting Text Color For Attributed Text:

let uiBarButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logOutTapped))
uiBarButton.setTitleTextAttributes([NSAttributedString.Key.foregroundColor : UIColor.appColor], for: .normal)
navigationItem.rightBarButtonItems = [uiBarButton]

Upvotes: 1

James Keating
James Keating

Reputation: 71

SWIFT 4

After you declare your custom barbuttonitem as an outlet:

@IBOutlet weak var yourBarButtonItem: UIBarButtonItem!

You can define your color however you like.

 yourBarButtonItem.tintColor = .red

Upvotes: 7

user5483739
user5483739

Reputation:

The problem was that the button was automatically set as custom. I refigured it to system.

Upvotes: 2

Related Questions