我试图改变设置按钮的颜色为白色,但不能让它改变。

这两种方法我都试过:

navigationItem.leftBarButtonItem?.tintColor = UIColor.whiteColor()
navigationItem.backBarButtonItem?.tintColor = UIColor.whiteColor()

但没有变化,它看起来仍然是这样的:

我怎么把那个按钮变成白色?


当前回答

所有的答案设置UINavigationBar.appearance()。tintColor与苹果在UIAppearance.h中的文档冲突。

注意:在iOS7上tintColor属性已经移动到UIView,现在有特殊的继承行为在UIView.h中描述。 这种继承的行为可能与外观代理发生冲突,因此现在外观代理不允许使用tintColor。

在Xcode中,你需要命令-点击你想要使用外观代理的每个属性来检查头文件,并确保该属性带有ui_appearance ance_selector注释。

因此,通过外观代理将导航栏染成紫色,标题和按钮染成白色的正确方法是:

UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().barTintColor = .purple
UINavigationBar.appearance().titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
UIBarButtonItem.appearance().tintColor = .white

注意UIBarButtonItem不是UIView的子类,而是NSObject。它的tintColor属性不是从UIView继承的tintColor。

不幸的是,UIBarButtonItem。tintColor没有使用ui_appearance ance_selector进行注释——但在我看来这是一个文档错误。苹果工程部门对此雷达的回应是支持的。

其他回答

在故事板中很容易设置:

你应该这样使用:

navigationController?.navigationBar.barTintColor = .purple
navigationController?.navigationBar.tintColor = .white

你只有一个选择把你的后退按钮藏起来,用你自己来做。 然后设置它的颜色。

我这样做了:

self.navigationItem.setHidesBackButton(true, animated: true)
let backbtn = UIBarButtonItem(title: "Back", style:UIBarButtonItemStyle.Plain, target: self, action: "backTapped:")
self.navigationItem.leftBarButtonItem = backbtn
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.grayColor()

这段代码更改箭头的颜色

self.navigationController.navigationBar.tintColor = UIColor.whiteColor();

如果这不起作用,请使用下面的代码:

self.navigationBar.barStyle = UIBarStyle.Black
self.navigationBar.tintColor = UIColor.whiteColor()

Swift 3 Notes

UIColor.whiteColor()和类似的被简化为UIColor.white

此外,许多以前的隐式可选项已被更改为显式,因此您可能需要:

self.navigationController?.navigationBar =

斯威夫特5.3:

UINavigationBar.appearance().backIndicatorImage = UIImage(named: "custom-back-image")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "custom-back-image")