添加自定义后退按钮对 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)

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

什_汗

在这种情况下,最好将其声明为实例变量,因为目标与局部变量一起丢失/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)
 }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章