长按手势识别(UILongPressGestureRecognizer)
以下创建手势将会添加到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 long = UILongPressGestureRecognizer(target: self, action: #selector(longAction))
设置最小的长按时间(1秒之后执行)
long.minimumPressDuration = 1.0
把长按手势添加到gestureView上
gestureView.addGestureRecognizer(long)
实现长按手势关联方法longAction
//MARK:- 长按手势关联方法
func longAction(sender:UILongPressGestureRecognizer){
//改变手势对象父视图的背景颜色
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
}
最终效果实现了,长按会改变整个view的颜色
长按之后