按钮触摸事件

Button touch Event

请检查以下代码。 我在 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")
}