OGeek|极客世界-中国程序员成长平台

标题: ios - 如何在导航栏中设置 backBarButtonItem 标题的样式? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:47
标题: ios - 如何在导航栏中设置 backBarButtonItem 标题的样式?

我希望能够仅更改导航栏中后退按钮的文本颜色。

作为一种解决方法,我可以通过创建自定义 View 并将其分配给 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")

导致属性:["NSColor": UIExtendedSRGBColorSpace 1 0 0 1].

我可以设置 tintColor 但这会改变除了标题之外的后退图标的颜色。

那么做我想做的最好的方法是什么?有什么办法吗?



Best Answer-推荐答案


我不确定我是否理解正确。但试试下面的代码。这将适用于您应用的所有栏按钮项。将此代码放置在应用程序生命周期内仅调用一次的位置。像 application:didFinishLaunchingWithOptions:

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

关于ios - 如何在导航栏中设置 backBarButtonItem 标题的样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46431592/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4