我正在尝试为我的按钮设置一个监听器功能,但我一直收到错误。以下是完成它的方式:
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")
}
}
有人知道我在哪里弄错了吗? :)
答案 0 :(得分:4)
你很亲密。只需替换
startButton.addTarget(self, action: "buttonPressed:" , for: .touchUpInside)
用这个:
startButton.addTarget(self, action: #selector(ViewController.buttonPressed(sender:)) , for: .touchUpInside)