UIButton causing unrecognized selector sent to instance

半世苍凉 提交于 2019-11-28 14:50:28

Your Selector(("buttonAction:")) might be the cause of your problem.

Try #selector(buttonAction(sender:)) instead.

use this

 func setUpButtons(){
        for i in 1...2 {


            let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 75, height: 100))
            btn.center = CGPoint(x: 20 + 100.0 * CGFloat(i), y: 200)
            btn.backgroundColor = UIColor.greenColor()
            btn.setTitle("click", forState: UIControlState.Normal)

            btn.addTarget(self, action:#selector(buttonAction), forControlEvents: .TouchUpInside)
            self.view.addSubview(btn)
        }
    }

for Swift 4 -

    override func awakeFromNib() {
        button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
    }

    @objc func buttonClicked(sender:UIButton) {
        ...
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!