为按钮添加触发事件
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 120,y: 120,width: 200,height: 30))
label.text = "我是一个便签控件"
self.view.addSubview(label)//把label添加到当前视图
let button = UIButton(type: UIButtonType.system)
button.frame = CGRect(x: 220,y: 240,width: 100,height: 30)
button.setTitle("按钮", for: UIControlState())
button.backgroundColor = UIColor.purple
self.view.addSubview(button)//把button添加到当前视图
button.addTarget(self,action: #selector(touchBegin),for:UIControlEvents.touchUpInside)//一个设计好了的,可以监听到用户的点击事件的函数
// Do any additional setup after loading the view, typically from a nib.
}
func touchBegin() {
print("用户点击了按钮")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
运行结果