使用自定义视图不工作为UIBarButtonItem添加目标

时间:2017-07-11 13:19:57

标签: ios swift xcode

你好,

我在向UIBarButtonItem添加自定义操作时遇到问题 目标不称为 有人看到了问题吗?

    let navBarMapImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
    navBarMapImageView.contentMode = .scaleAspectFit
    navBarMapImageView.image = image
    navBarMapImageView.isUserInteractionEnabled = true
    navBarMapImageView.target(forAction: #selector(openMaps), withSender: self)
    let navBarMapButton = UIBarButtonItem(customView: navBarMapImageView)

感谢您的帮助

5 个答案:

答案 0 :(得分:4)

您要将目标添加到UIImageView,这不起作用请查看以下代码

    let btn1 = UIButton(type: .custom)
    btn1.setImage(UIImage(named: "imagename"), for: .normal)
    btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
    btn1.addTarget(self, action: #selector(openMaps), for: .touchUpInside)
    let item1 = UIBarButtonItem(customView: btn1)

    self.navigationItem.setRightBarButtonItems([item1], animated: true)

答案 1 :(得分:1)

为什么不直接使用UIButton并将其指定为此按钮中建议的条形按钮项目:

UIBarButtonItem: target-action not working?

    let button  = UIButton(type: .custom)
    if let image = UIImage(named:"icon-menu.png") {
        button.setImage(image, for: .normal)
    }

    button.frame = CGRect(x:0.0, y:0.0, width: 30.0, height: 30.0)
    button.addTarget(self, action: #selector(MyClass.myMethod), for: .touchUpInside)
    let barButton = UIBarButtonItem(customView: button)
    navigationItem.leftBarButtonItem = barButton

答案 2 :(得分:1)

将目标设置为navBarMapButton,而不是navBarMapImageView

答案 3 :(得分:1)

我想添加另一种方法。

您可以创建一些自定义栏项目类,并为customView编写特定的初始化程序。例如;

fileprivate class BarButtonItem: UIBarButtonItem {

    @objc func buttonAction()

    override init() {
        super.init()
    }

    convenience init(customView: UIControl) {
        self.init()
        self.customView = customView
        customView.addTarget(self, action: .onBarButtonAction, for: .touchUpInside)
    }

fileprivate extension Selector {
    static let onBarButtonAction = #selector(BarButtonItem.buttonAction)
}

通过这种方式,您甚至可以在buttonAction中添加闭包。

var actionCallback: ( () -> Void )?
    @objc func buttonAction() {
        actionCallback?()
    }

答案 4 :(得分:0)

您要将目标添加到navBarMapImageView,但您应该将目标添加到navBarMapButton

let navBarMapImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
navBarMapImageView.contentMode = .scaleAspectFit
navBarMapImageView.image = image
navBarMapImageView.isUserInteractionEnabled = true
//navBarMapImageView.target(forAction: #selector(openMaps), withSender: self)
let navBarMapButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(openMaps))