首页 > 解决方案 > Swift hide back button

问题描述

I need to hide back button and paste another button

self.navigationItem.setHidesBackButton(true, animated: false)
self.navigationItem.hidesBackButton = true
self.navigationController?.navigationItem.hidesBackButton = true
self.navigationController?.navigationBar.topItem?.hidesBackButton = true

self.tabBarController?.navigationController?.navigationItem.hidesBackButton = true
self.tabBarController?.navigationController?.navigationItem.setHidesBackButton(true, animated: false)
self.tabBarController?.navigationItem.hidesBackButton = true

let backButton1 = UIBarButtonItem (title: "Button", style: .plain, target: self, action: #selector(GoToBack))
self.navigationItem.leftBarButtonItem = backButton1
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(GoToBack))

self.tabBarController?.navigationItem.setLeftBarButtonItems([backButton1], animated: true)

but this code didnt work, back button dont hided or replaced to another button

how can i solve this problem ?

show this vc like this

self.navigationController?.pushViewController(viewcontroller, animated: true)

标签: swift

解决方案


首先,BaseViewController在您的项目中创建并设置 backButton 隐藏代码并在viewDidLoad.

之后,您项目的所有控制器都应该继承自所有控制器的BaseViewController新后退按钮。

基本视图控制器

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true 
    self.setBackButton()// Set Custom back button
}

设置自定义后退按钮代码

//Add Custom Back Button
fileprivate func setBackButton() {
    let button   = UIButton(type: UIButton.ButtonType.custom) as UIButton
    button.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
    button.contentHorizontalAlignment = .fill
    button.contentVerticalAlignment = .fill
    button.imageView?.contentMode = .center
    button.contentEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)

    button.setImage(UIImage(named: "backButton.png"), for: .normal)
    button.addTarget(self, action: #selector(btnBackActionHandler(_:)), for:.touchUpInside)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)

}


@objc func btnBackActionHandler(_ sender : AnyObject) {
    self.navigationController?.popViewController(animated: true)
}

推荐阅读