导航栏按钮不显示在导航栏中

Navigation bar button doesn't show in navigationbar

我以编程方式在 navigationBar 上设置了 rightBarButton,但没有显示,尽管标题显示正常。

这是我的代码形式 AppDelegate:

    UINavigationBar.appearance().barTintColor        = APP_COLOR
    UINavigationBar.appearance().tintColor           = UIColor.white
    UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.font:Constants.APP_REGULAR_FONT_WITH_SIZE(size: 18), NSAttributedString.Key.foregroundColor : UIColor.white]

这是我的 viewController 中的代码,我试图在其中添加 rightBarButton

override func viewDidLoad()
{
    super.viewDidLoad()

    let rightBarButton = UIBarButtonItem(image: UIImage(named: "logout"), style: .plain, target: self, action: #selector(logoutButtonTapped))
    self.navigationController?.navigationItem.rightBarButtonItem = rightBarButton
}

我也试过删除外观设置,但按钮仍然不可见。

您可以在代码中删除 self.navigationController?.

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(logoutButtonTapped))
}

不要使用 self.navigationController?.navi... 而不是使用 self.navigationItem.rightBarButton...

override func viewDidLoad()
{
    super.viewDidLoad()

    let rightBarButton = UIBarButtonItem(image: UIImage(named: "logout"), style: .plain, target: self, action: #selector(logoutButtonTapped))
    self.navigationItem.rightBarButtonItem = rightBarButton
}

希望这段代码能解决您的问题。谢谢。

     let rightBarButton = UIBarButtonItem(image: UIImage(named: "test"), style: .plain, target: self, action: #selector(logoutButtonTapped))

    self.navigationController?.navigationBar.topItem?.rightBarButtonItem = rightBarButton

现在这对我有用