Swift 2.1 为 UIView 添加点击事件和点击效果
前言
UIView不像UIButton加了点击事件就会有点击效果,体验要差不少,这里分别通过自定义和扩展来实现类似UIButton的效果。
正文
一、为UIView添加点击事件
extensionUIView{
funcaddOnClickListener(target:AnyObject,action:Selector){
letgr=UITapGestureRecognizer(target:target,action:action)
gr.numberOfTapsRequired=1
userInteractionEnabled=true
addGestureRecognizer(gr)
}
}
二、为UIView添加点击效果
classUIViewEffect:UIView{
overridefunctouchesBegan(touches:Set<UITouch>,withEventevent:UIEvent?){
backgroundColor=UIColor.groupTableViewBackgroundColor()
}
overridefunctouchesCancelled(touches:Set<UITouch>?,withEventevent:UIEvent?){
UIView.animateWithDuration(0.15,animations:{()->Voidin
self.backgroundColor=UIColor.clearColor()
})
}
overridefunctouchesEnded(touches:Set<UITouch>,withEventevent:UIEvent?){
UIView.animateWithDuration(0.15,animations:{()->Voidin
self.backgroundColor=UIColor.clearColor()
})
}
}
这里大家可以换成自己的点击效果,如果是UIImageView可以换成点击变更透明度。