我试图为我的按钮设置一个侦听器功能,但我一直遇到错误。这是怎么做的:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        //Create the BackGround
       self.view.backgroundColor = UIColor.black
        let startButton = UIButton()
        startButton.setTitle( " start ", for: UIControlState.normal)
        startButton.setTitleColor(UIColor.blue, for: UIControlState.normal)
        startButton.frame = CGRect(x: 10, y:40 , width: 250, height: 25)
        self.view.addSubview(startButton)

        startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)


    }


    func buttonPressed(sender: UIButton!) {
        print("hello")
    }


}

有人知道我在哪里犯错吗? :)

最佳答案

你近了只需更换

startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)

有了这个:
startButton.addTarget(self, action: #selector(ViewController.buttonPressed(sender:)) , for: .touchUpInside)

关于ios - 如何在Swift 3中为以编程方式定义的按钮设置监听器功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39961299/

10-14 22:41