Swift 导航栏中的自定义后退按钮

Swift custom back button in navigation bar

我正在尝试为导航栏中的后退按钮使用自定义图像。我正在使用下面的代码,它添加了图像,但还在按钮中保留了文本 "Back"。我也想删除文本。我可以这样做吗?

self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "icon-back")
self.navigationController?.navigationBar.backIndicatorTransitionMaskImage = UIImage(named: "icon-back")
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)

试试下面的代码:-)

func SetBackBarButtonCustom()
{
    //Back buttion
    let btnLeftMenu: UIButton = UIButton()
    btnLeftMenu.setImage(UIImage(named: "back_arrow"), for: UIControlState())
    btnLeftMenu.addTarget(self, action: #selector(UIViewController.onClcikBack), for: UIControlEvents.touchUpInside)
    btnLeftMenu.frame = CGRect(x: 0, y: 0, width: 33/2, height: 27/2)
    let barButton = UIBarButtonItem(customView: btnLeftMenu)
    self.navigationItem.leftBarButtonItem = barButton
}

func onClcikBack()
{
    _ = self.navigationController?.popViewController(animated: true)
}

如果您想在每个 UIViewController 中添加后退按钮,那么您可以在 UIViewController 扩展中添加代码,否则您可以直接使用 addBackButton(),如下所示。

extension UIViewController {

    func addBackButton() {
        let btnLeftMenu: UIButton = UIButton()
        let image = UIImage(named: "backButtonImage");
        btnLeftMenu.setImage(image, for: .normal)
        btnLeftMenu.setTitle("Back".localized, for: .normal);
        btnLeftMenu.sizeToFit()
        btnLeftMenu.addTarget(self, action: #selector (backButtonClick(sender:)), for: .touchUpInside)
        let barButton = UIBarButtonItem(customView: btnLeftMenu)
        self.navigationItem.leftBarButtonItem = barButton
    }

    func backButtonClick(sender : UIButton) {
        self.navigationController?.popViewController(animated: true);
    }
}

确保您应该在您的应用程序包中添加以下文件 "backButtonImage.png"。

在自定义 UIViewController 的 viewDidLoad 方法中调用此方法 self.addBackButton() class 像这样

override func viewDidLoad() {
         super.viewDidLoad()
         self.addBackButton()
 }

注意:如果您不在扩展中添加 addBackButton 方法,那么您需要直接在 class 中添加此方法,并相应地设置目标和选择器。