如何在UINavigationController中推送的视图控制器的所有后退按钮上设置自定义图像?
我的问题是:
leftBarButtonItem
,位置明智(因为backBarButtonItem
本身太粘在左边,我似乎无法改变它的水平对齐方式。)setCustomBackButton
并在每个视图控制器上调用它也不是一个选项,我正在寻找类似UINavigationBar.appearance()
的内容,即整个应用程序。答案 0 :(得分:2)
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "backArrow")
见这里:https://www.raywenderlich.com/108766/uiappearance-tutorial
答案 1 :(得分:1)
根据以下OP
答案给出答案:
Custom Back Button With Image和How to remove all navigationbar back button title
在didFinishLaunchingWithOptions
中的AppDelegate
方法中尝试以下代码。
设置自定义后退按钮:
let backArrowImage = UIImage(named: "back") // set your back button image here
let renderedImage = backArrowImage?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = renderedImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = renderedImage
隐藏后退按钮标题:
let barAppearace = UIBarButtonItem.appearance()
barAppearace.setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), for:UIBarMetrics.default)
输出 Updated
<强>更新强>
您需要将以下代码添加到More Information
viewController以保留title position
。
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
答案 2 :(得分:1)
您可以创建自己的UINavigationController
子类并更改navigationController(_:willShow:animated:)
委托方法中的按钮,如下所示:
class MyNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
interactivePopGestureRecognizer?.delegate = self
}
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController != self.viewControllers.first { // don't add button to rootViewController
let backButton = UIBarButtonItem(image: UIImage(named: "backArrow"), style: .plain, target: self, action: #selector(popViewController(animated:)) )
viewController.navigationItem.leftBarButtonItem = backButton
}
}
}
理论上,上面的委托方法可以在任何地方生活,但这种方式可以在逻辑上轻松选择您希望拥有此功能的位置。
另外,请不要忘记设置interactivePopGestureRecognizer
代表,不要丢失边缘滑动手势(这在设置新的leftBarButtonItem时会以某种方式中断)。
上述方法可以通过跟踪已经显示的视图控制器进一步改进,然后只替换新的视图控制器上的leftBarButtonItem(现在它也在返回/弹出到已经显示的视图控制器时替换它)。 / p>
答案 3 :(得分:0)
尝试这个Swift 4.2
extension YouFirstViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if !(viewController is YouFirstViewController) {
let backButton = UIBarButtonItem(image: UIImage(named: "icnBack"), style: .plain, target: self, action: #selector(popview))
viewController.navigationItem.leftBarButtonItem = backButton
}
}
@objc func popview() {
navigationController?.popViewController(animated: true)
}
}
onYouFirstViewController
class YouFirstViewController: UIViewcontroller {
override func viewDidLoad() {
self.navigationController?.delegate = self
}
}