如何在swift 3中以编程方式为按钮设置监听器功能

时间:2016-10-10 15:04:31

标签: ios button uibutton swift3

我正在尝试为我的按钮设置一个监听器功能,但我一直收到错误。以下是完成它的方式:

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")
    }


}

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

1 个答案:

答案 0 :(得分:4)

你很亲密。只需替换

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

用这个:

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