轻扫手势识别UISwipeGestureRecognizer
以下创建手势将会添加到gestureView上
//将view的背景颜色设置为白色
self.view.backgroundColor = UIColor.white
//创建一个UIView
let gestureView = UIView(frame: CGRect(x: 0, y: 100, width:
308, height: 308))
gestureView.backgroundColor = UIColor.green
self.view.addSubview(gestureView)
创建轻扫手势
let swipe = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction))
设置手势支持的轻扫方向,而且一个轻扫手势只能存储一个方向
swipe.direction = .right
let swipe2 = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction))
swipe.direction = .left
把轻扫手势添加到gestureView上
gestureView.addGestureRecognizer(swipe)
gestureView.addGestureRecognizer(swipe2)
实现轻扫手势关联方法swipeAction
//MARK:- 轻扫手势关联方法
func swipeAction(sender:UISwipeGestureRecognizer){
if sender.direction == .right{
sender.view?.backgroundColor = backRandomColor()
}
else if sender.direction == .left {
sender.view?.superview?.backgroundColor = backRandomColor()
}
}
定义一个backRandomColor方法用来随机变换背景颜色
func backRandomColor()->UIColor {
//产生0~1的随机数
let redView = Float(arc4random_uniform(256))/255.0
let greenView = Float(arc4random_uniform(256))/255.0
let blueView = Float(arc4random_uniform(256))/255.0
//产生随机颜色
let color = UIColor(red: CGFloat(redView), green: CGFloat(greenView), blue: CGFloat(blueView), alpha: 1.0)
return color
}
网友评论