2017-07-11 74 views
2

你好,

我有一個問題與添加自定義操作到的UIBarButtonItem
目標不叫
是不是有人看這個問題?的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) 

感謝您的幫助

+0

爲什麼使用UIImageView,而是使用UIButton。 – Nilesh

+0

是的,很好的問題,我不知道爲什麼 與按鈕肯定是更好的方法:-D – auryn31

+0

因爲UIImageView不是一個控件,你不能添加控件事件的目標。 – Nilesh

回答

3

你加入目標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

你爲什麼不只是使用一個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 
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)) 
1

目標設置爲navBarMapButton,而不是到navBarMapImageView

相關問題