繁体   English   中英

在不同屏幕上更改导航栏颜色和标题颜色

[英]Change navigationbar color & title color on different screens

在我的 iPhone 应用程序中,我有两个 NavigationC0nroller 背景颜色和标题颜色

  1. 白色背景+红色标题
  2. 清晰的颜色背景 + 白色标题

我正在使用如下通用代码来更改背景颜色和标题颜色

@objc class Helper : NSObject{
class func restNavigationBarWithNavigationController(navigationController : UINavigationController , withColor : UIColor,isTranslucent : Bool )
{
    navigationController.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController.navigationBar.shadowImage = UIImage()
    navigationController.navigationBar.isTranslucent = isTranslucent
    navigationController.view.backgroundColor = withColor
    navigationController.navigationBar.backgroundColor = withColor
}
}

我在视图控制器的 viewdidload 和 ViewWillAppear 中调用上面,如下所示

self.navigationController?.navigationBar.tintColor = .white

Helper.restNavigationBarWithNavigationController(navigationController: 
self.navigationController!, withColor: .clear, isTranslucent: true)

但是上面的代码不起作用如果我从白色弹出一个屏幕到红色标题&反之亦然。

请让我知道我在这里做错了什么。

任何想法或建议都会很棒。 (仅供参考:我在 Objective-c 视图控制器中使用相同的代码库)

好吧,如果您想更改每个屏幕中的导航栏样式,可以使用以下代码:

class FirstViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // White color Background + Red Color Title
        navigationController.navigationBar.barTintColor = .white
        navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red]
    }
}

// 下一个

class SecondViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Clear color Background + White color title
        navigationController.navigationBar.barTintColor = .clear
        navigationController.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
    }
}

这适用于 Swift 4

Swift 5 将NSAttributedStringKey类型分离为NSAttributedString.Key并使用如下(Swift 5.1.3)。

func configureNavigationBar() {
      navigationController?.navigationBar.barTintColor = .darkGray
      navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM