请检查以下代码。 我在 mainView 上制作了按钮。 但是按钮不会调用“thumbsUpButtonPressed”方法。 请检查!
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .custom)
button.frame = CGRect(x: 60, y: 100, width: 50, height: 50)
button.backgroundColor = .red //.clear
button.layer.cornerRadius = 5
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.black.cgColor
button.clipsToBounds = true
//button.setImage(UIImage(named:"thumbsUp.png"), for: .normal)
button.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchDown)
view.addSubview(button)
}
func thumbsUpButtonPressed(sender: UIButton) {
print("thumbs up button pressed")
}
最佳答案
如果您想将按钮作为参数传递,您必须在选择器中指定它。为此,您可以在方法名称后添加 (_:)
。
尝试:
button.addTarget(self, action: #selector(thumbsUpButtonPressed(_:)), for: .touchDown)
如果您希望它与您现有的代码一起工作,您需要更改您的方法以不接受按钮作为参数,如下所示:
func thumbsUpButtonPressed() {
print("thumbs up button pressed")
}
关于ios - 按钮触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788348/