除UIButton外的UI组件,addGestureRecognizer的方法,代码如下:
//定义view
let view = UIView(frame:CGRect(x:100, y:50, width:200, height:50))
view.text = "按钮"
//定义一个UITapGestureRecognizer
let tap = UITapGestureRecognizer(target:self, action:Selector("tapClick:"))
//设置view可以点击
view.userInteractionEnabled=true
//给view添加事件
view.addGestureRecognizer(tap)
//事件的代码
func tapClick(sender:UIView){
print("按钮被点击")
}
UIButton添加点击事件,代码如下:
//定义btn
let btn =UIButton(frame:CGRect(x:100, y:50, width:200, height:50))
btn.setTitle("按钮", forState: .Normal)
//btn添加点击事件
btn.addTarget(self, action:"btnClick:", forControlEvents:UIControlEvents.TouchUpInside)
//事件的代码
func btnClick(sender:UIButton){
print("按钮被点击")
}