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

时间:2016-05-10 13:40:49

标签: swift uinavigationbar uibarbuttonitem back-button

我正在尝试在导航栏中使用自定义图像作为后退按钮。我使用下面的代码,它添加了图像,但也保留了文本" 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)

2 个答案:

答案 0 :(得分:6)

尝试以下代码:-)

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)
}

答案 1 :(得分:3)

如果你想在每个UIViewController中添加Back按钮,那么你可以在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(),如下所示

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

注意:如果你没有在扩展中添加addBackButton方法,那么你需要在类中直接添加这个方法,并相应地设置target和Selector。