如何在Swift中更改UIBarButtonItem的tintColor?

9
我想把右侧栏按钮项的颜色从黑色变为白色。它是一个搜索图标按钮。我还没有编写搜索实现,因为我想先完成主界面。我认为我已经编写了正确的代码,因此它应该显示为白色,但是在故事板和模拟器中似乎仍然显示为黑色。
在故事板中,我也将其设置为白色。
以下是我的代码,位于AppDelegate.swift文件中:
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
}

这是模拟器的图像:

enter image description here

我觉得很奇怪,这行代码不起作用。有什么解决办法吗?


1
你试过UIBarButtonItem.appearance().tintColor = UIColor.greenColor()吗? - Rashwan L
@RashwanL 我试过了,但它仍然是黑色的。我想让它变成白色。 - user5483739
UINavigationBar.appearance().tintColor = UIColor.whiteColor() 应该可以工作。你必须在代码的某个地方将 tintColor 更改为其他颜色。 - Leo
@Leo 这个不起作用。 - user5483739
3个回答

7

SWIFT 4

在将自定义的barbuttonitem声明为outlet后:
@IBOutlet weak var yourBarButtonItem: UIBarButtonItem!

你可以随意定义自己的颜色。
 yourBarButtonItem.tintColor = .red

2
问题在于按钮自动设置为了“自定义(custom)”,我将其重新配置为“系统(system)”。

1
设置普通文本的文本颜色:
let uiBarButton = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(logOutTapped))
uiBarButton.tintColor = UIColor.appColor
navigationItem.rightBarButtonItems = [uiBarButton]

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接