添加自定义后退按钮不适用于UINavigationBar

时间:2018-02-16 23:38:19

标签: ios swift uinavigationbar

我正在尝试向导航控制器添加自定义后退按钮,但它无法正常运行。

func setupNavBarItems() {
    self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    self.navigationController?.navigationBar.shadowImage = UIImage()
    self.navigationController?.navigationBar.isTranslucent = true
    self.navigationController?.view.backgroundColor = UIColor.clear

    let backButton = UIButton(type: .system)
    backButton.setImage(#imageLiteral(resourceName: "icon_back"), for: .normal)
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
}

我也没试过就试过这个(我用以下代码替换了底部的2行)

    let backButton = UIButton(type: .system)
    backButton.setImage(#imageLiteral(resourceName: "icon_back"), for: .normal)
    let backBarButton = UIBarButtonItem.init(customView: backButton)
    navigationItem.setLeftBarButton(backBarButton, animated: true)

我看到自定义按钮图像,但它不会触发后退按钮操作。

1 个答案:

答案 0 :(得分:1)

在这种情况下,最好将其声明为实例变量,因为除了目标lazy

之外,目标变为局部变量/ popViewController
let addButton = UIBarButtonItem(image:UIImage(named:"your_icon_name"), style:.plain, target:self, action:#selector(YourControllerName.buttonAction(_:)))
addButton.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem = addButton

.....

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