Ios addTarget无法正常工作
当我以编程方式交换按钮时,addTarget无法正常工作Ios addTarget无法正常工作,ios,swift,Ios,Swift,当我以编程方式交换按钮时,addTarget无法正常工作 let leftButton: UIButton = UIButton(type: UIButtonType.custom) leftButton.setImage(UIImage(named: "menu"), for: UIControlState.normal) leftButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
let leftButton: UIButton = UIButton(type: UIButtonType.custom)
leftButton.setImage(UIImage(named: "menu"), for: UIControlState.normal)
leftButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
...
leftButton.addTarget(nil, action: #selector(MapViewController.backToModules(sender:)), for: UIControlEvents.touchUpInside)
...
let leftBarButton = UIBarButtonItem(customView: leftButton)
let rightBarButton = UIBarButtonItem(customView: rightButton)
//assign button to navigationbar
self.navigationItem.rightBarButtonItems = [rightBarButton]
self.navigationItem.leftBarButtonItem = leftBarButton
我的目标应该调用以下函数,但它没有
func backToModules(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
您缺少目标参数(我假定它是
self
):
添加目标时,您必须指定确定要调用的方法标识符的选择器
——您已经做到了这一点。然而,您还必须给它一个目标对象,一个应该调用选择器的对象,并且您指定为nil
。这意味着在nil
对象上调用了选择器
在您的情况下,第一个目标参数必须是类型为
MapViewController
的对象,将在该对象上调用选择器定义的方法(backToModules(sender:)
)。如果您在应该是目标的MapViewController
实例的上下文中调用该addTarget
方法,那么按照我的建议使用self
。说它根本没有被调用是不对的<代码>无有针对性的行动是一件事。如果在响应程序链中找到选择器的处理程序,那么它确实会被调用。
leftButton.addTarget(self, action: #selector(MapViewController.backToModules(sender:)), for: UIControlEvents.touchUpInside)