Helenr
以下是UIButton使用targetAction以编程方式添加的完整解决方案。Swift 2.2override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .greenColor() button.setTitle("Test Button", forState: .Normal) button.addTarget(self, action: #selector(buttonAction), forControlEvents: .TouchUpInside) self.view.addSubview(button)}func buttonAction(sender: UIButton!) { print("Button tapped")}使用NSLayoutConstraint而不是frame为每个iPhone屏幕正确放置按钮可能更好。更新了Swift 3.1的代码:override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .green button.setTitle("Test Button", for: .normal) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) self.view.addSubview(button)}func buttonAction(sender: UIButton!) { print("Button tapped")}更新了Swift 4.2的代码:override func viewDidLoad() { super.viewDidLoad() let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50)) button.backgroundColor = .green button.setTitle("Test Button", for: .normal) button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside) self.view.addSubview(button)}@objc func buttonAction(sender: UIButton!) { print("Button tapped")}如果func buttonAction声明private或上述仍然有效internal。