以编程方式添加到导航栏的UIBarButtonItem无法调用选择器,而添加到工具栏的按钮确实如此

时间:2017-12-21 20:47:39

标签: ios swift uinavigationcontroller uibarbuttonitem

我有一个令人困惑的问题。在我的应用程序中,我有一个工具栏,可以以编程方式交换按钮并正确调用关联的选择器。但是,当我将相同的技术应用于导航栏上的按钮时,它无法调用选择器。以下示例代码包含2组按钮(一组用于导航,一组用于工具栏)。尽管相同,导航栏按钮上的选择器永远不会被调用。

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var toolbar: UIToolbar!

    let navCancelButton = UIBarButtonItem(barButtonSystemItem: .cancel,
                                          target: self,
                                          action: #selector(toggleDelete))
    let navTrashButton = UIBarButtonItem(barButtonSystemItem: .trash,
                                         target: self,
                                         action: #selector(toggleDelete))

    let toolbarCancelButton = UIBarButtonItem(barButtonSystemItem: .cancel,
                                              target: self,
                                              action: #selector(toggleDelete))
    let toolbarTrashButton = UIBarButtonItem(barButtonSystemItem: .trash,
                                             target: self,
                                             action: #selector(toggleDelete))

    var isDeleting = false {
        didSet {
            navigationItem.rightBarButtonItem = isDeleting ? navCancelButton : navTrashButton
            toolbar.items = isDeleting ? [toolbarCancelButton] : [toolbarTrashButton]
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        isDeleting = false
    }

    @objc func toggleDelete() {
        isDeleting = !isDeleting
    }
}

这显示了之前的代码:

enter image description here

2 个答案:

答案 0 :(得分:3)

导航栏中的按钮似乎失去了目标。所以你可以像这样在viewDidLoad中设置目标:

self.navTrashButton.target = self
self.navCancelButton.target = self

或者我要做的就是将变量放在类范围中,如下所示:

var navCancelButton: UIBarButtonItem!
var navTrashButton: UIBarButtonItem!

然后在viewDidLoad中创建它们:

navCancelButton = UIBarButtonItem(barButtonSystemItem: .cancel,
                                  target: self,
                                  action: #selector(toggleDelete))
navTrashButton = UIBarButtonItem(barButtonSystemItem: .trash,
                                 target: self,
                                 action: #selector(toggleDelete))

通过这种方式,您可以知道当视图控制器期望它们为它们做好准备时,正在创建按钮。

答案 1 :(得分:2)

事实是目标正在丢失,它可能是一个错误",可能的解决方法是使用lazy var

lazy var navCancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self,  action: #selector(toggleDelete))
lazy var navTrashButton = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(toggleDelete))