我有一个 UINavigationItem
我正在尝试显示一个 UIBarButtonItem
。
现在的问题是我正确地添加了它们,它们正常工作并且 100% 正常工作。
但它们没有显示在 UINavigationBar
上。
现在,对于流程,我正在执行以下操作。
1- 我隐藏了后退按钮,像这样
self.navigationItem.setHidesBackButton(isBackHidden, animated: false)
2- 当用户点击 UIButton
时,我在运行时使用函数动态添加这 2 个按钮。
let rightBarItem = UIBarButtonItem(title: "Button.Done".localized, style: .plain, target: self, action: #selector(self.saveButtonTapped))
navigationItem.rightBarButtonItem = rightBarItem
let leftBarItem = UIBarButtonItem(title: "Button.Cancel".localized, style: .plain, target: self, action: #selector(self.cancelButtonTapped))
navigationItem.rightBarButtonItem?.tintColor = .red // still nothing
navigationItem.leftBarButtonItem = leftBarItem
3- 我已经尝试使用这些功能,但结果仍然相同
self.navigationItem.setLeftBarButton(UIBarButtonItem?, animated: Bool)
self.navigationItem.setRightBarButton(UIBarButtonItem?, animated: Bool)
总结:
我曾尝试更改 tintColor
,因为它们的功能正常,我认为这是一个颜色问题。
我曾尝试在 DispatchQueue.main.async {}
中使用它们,认为这可能是线程问题,因为它是动态的。
我已经调试并检查了 UINavigationItem
中的项目,它们存在。
主要是怎么回事:
按钮未显示,但在 UINavigationItem
上点击它们的位置时它们工作正常。
最佳答案
Now the problem is i added them correctly, they're functional and working 100%.
but they're not showing on the UINavigationBar.
根据您提到的情况,这只是一个 UI 问题 - 原因不明-。
因此,要确认导航项中将显示按钮项,您可以做的是让栏按钮项具有自定义 View 。添加一个 UIButton
作为 UIBarButtonItem
的自定义 View 是有效的,如下所示:
// right
let rightButton = UIButton(type: .custom)
rightButton.setTitle("Button.Done".localized, for: .normal)
rightButton.addTarget(self, action: #selector(saveButtonTapped), for: .touchUpInside)
let rightBarButtonItem = UIBarButtonItem(customView: rightButton)
navigationItem.setRightBarButton(rightBarButtonItem, animated: true)
// left
let leftButton = UIButton(type: .custom)
leftButton.setTitle("Button.Cancel".localized, for: .normal)
leftButton.addTarget(self, action: #selector(cancelButtonTapped), for: .touchUpInside)
let leftBarButtonItem = UIBarButtonItem(customView: leftButton)
navigationItem.setLeftBarButton(leftBarButtonItem, animated: true)
因此,对于任何需要的 UI 更新,您可以编辑 rightButton
和 leftButton
,例如:
leftButton.layer.backgroundColor = UIColor.red.cgColor
leftButton.layer.borderWidth = 2.0
leftButton.layer.borderColor = UIColor.black.cgColor
此外,我假设没有必要调用:
self.navigationItem.setHidesBackButton(isBackHidden, animated: false)
在设置左栏按钮项目时,默认情况下它应该是后退按钮的替代品。
关于ios - navigationItem 按钮不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126284/