2017-09-26 152 views
2

我希望只能更改導航欄中後退按鈕的文本顏色。如何在導航欄中設置backBarButtonItem標題的樣式?

作爲一種解決方法,我可以通過創建自定義視圖並將其分配給navigationItem.leftBarButtonItem來完成我想要做的事情,但它看起來不太好,我也失去了滑動到彈出的能力。 enter image description here

代碼上面:

let button = UIButton(type: .system) 
    let originalImage = #imageLiteral(resourceName: "BackButton") 
    let scaledImage: UIImage = UIImage(cgImage: originalImage.cgImage!, scale: 30, orientation: originalImage.imageOrientation) 

    button.setImage(scaledImage, for: .normal) 
    button.setTitle("YourTitle", for: .normal) 
    button.sizeToFit() 
    button.setTitleColor(.brown, for: .normal) 
    button.tintColor = .blue 

    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button) 

我也看到的東西像建議通過

navigationController?.navigationBar.topItem.backBarButtonItem?.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: .normal) 

設置後退按鈕的屬性,但是這似乎並沒有對任何影響外觀儘管

print("Attributes: ", navigationController?.navigationBar.topItem?.backBarButtonItem?.titleTextAttributes(for: .normal) ?? "No attributes") 

resulti ng Attributes: ["NSColor": UIExtendedSRGBColorSpace 1 0 0 1]

我可以設置tintColor但是除了標題之外,這會改變背面圖標的顏色。

那麼做我想做的事情的最佳方式是什麼?有沒有辦法?

回答

0

我想通了。您可以通過在前一個視圖控制器中設置self.navigationItem.backBarButtonItem來設置後退按鈕的樣式。

例如,在我的情況下,我有TableViewController,當您單擊某個單元格時,該應用程序將轉換爲ViewController。在TableViewController我有

public func changeColor() { 
    let barButton = UIBarButtonItem(title: "Anything", style: .plain, target: nil, action: nil) 
    barButton.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.brown], for: .normal) 

    self.navigationItem.backBarButtonItem = barButton 
} 

,然後在ViewController

@IBAction func buttonPressed(_ sender: Any) { 
    let vc = self.navigationController?.viewControllers[0] as! TableViewController 
    vc.changeColor() 
    self.title = "hello very long title asdfasdfasfdasdfasdfasdfasdfasdf" 
} 

其結果是,在ViewController按下一個按鈕,將改變其返回按鈕,棕色的標題的顏色。

0

我不確定我是否正確理解你。但請嘗試下面的代碼。這將應用於您應用的所有酒吧按鈕項目。將此代碼放在應用程序生命週期內僅調用一次的地方。像application: didFinishLaunchingWithOptions:

let attribs = [NSForegroundColorAttributeName: UIColor.red, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18)] 
UIBarButtonItem.appearance().setTitleTextAttributes(attribs, for: .normal) 
+0

您的解決方案將更改整個應用程序中的酒吧按鈕項目的顏色。我只是想在一個視圖控制器中更改後退按鈕的顏色。看到我的答案。 還是謝謝! – TWOF