【问题标题】:Adding custom back button not working to UINavigationBar将自定义后退按钮添加到 UINavigationBar 不起作用
【发布时间】:2018-07-27 22:19:01
【问题描述】:

我正在尝试将自定义后退按钮添加到我的导航控制器,但它无法正常工作。

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)

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

【问题讨论】:

  • 您需要手动执行返回操作,例如self.navigationController.popViewController

标签: ios swift uinavigationbar


【解决方案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)
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 2013-03-18
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多