簡體   English   中英

如何在Swift中更改UIBarButtonItem的tintColor?

[英]How to change tintColor of UIBarButtonItem in Swift?

我想將右欄按鈕項的顏色從黑色更改為白色。 它是一個按鈕作為搜索圖標。 我還沒有對搜索實現進行編碼,因為我想首先完成主界面。 我以為我寫了正確的代碼所以它應該顯示為白色,但它在故事板和模擬器中似乎仍然顯示為黑色。

在故事板中,我還將其設置為白色。

這是我的代碼,它位於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
}

這是模擬器的圖像:

在此輸入圖像描述

我發現這行代碼不起作用很奇怪。 有解決方案嗎

SWIFT 4

將自定義barbuttonitem聲明為插座后:

@IBOutlet weak var yourBarButtonItem: UIBarButtonItem!

您可以根據需要定義顏色。

 yourBarButtonItem.tintColor = .red

問題是按鈕自動設置為自定義。 我把它重新配置成系統。

設置普通文本的文本顏色:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM