import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = #colorLiteral(red: 1, green: 0.7982094178, blue: 0.7911132384, alpha: 1)
let gestureView = UIView(frame:CGRect(x: 50, y: 100, width: 308, height: 308))
gestureView.backgroundColor = #colorLiteral(red: 0.7828073154, green: 1, blue: 0.9114280926, alpha: 1)
self.view.addSubview(gestureView)
//手势一共有七种:轻拍,长按,平移,缩放,旋转,捏合,屏幕边缘。
//重点:轻拍,长按,缩放
/*
//轻拍手势:能识别出用户的轻拍操作
let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
//设置轻拍要求的最低次数
tap.numberOfTapsRequired = 1
//设置轻拍需求的手指个数,
//苹果设备最多支持11个手指对象进行触摸
tap.numberOfTouchesRequired = 1
//添加轻拍手势
gestureView.addGestureRecognizer(tap)
*/
/*
//长按手势
let long = UILongPressGestureRecognizer(target: self, action: #selector(longAction))
//设置最小长按时间
long.minimumPressDuration = 1.0
//把长按手势添加到gestureView上
gestureView.addGestureRecognizer(long)
*/
//平移手势
let pan = UIPanGestureRecognizer(target: self, action: #selector(panAction))
//把平移手势添加到gestureView上
gestureView.addGestureRecognizer(pan)
}
//MARK:- 平移手势的关联方法
func panAction(sender:UIPanGestureRecognizer) {
//1. 获取手势在视图上的平移增量
let point = sender.translation(in: sender.view)
//2.让手势所在的视图对象做仿射变换
sender.view?.transform = (sender.view?.transform.translatedBy(x: point.x, y: point.y))!
//3.将上次的平移增量置为0
sender.setTranslation(CGPoint(), in: sender.view)
}
//MARK:- 长按手势的关联方法
func longAction(sender:UILongPressGestureRecognizer) {
//改变手势对象父视图的背景颜色
sender.view?.superview?.backgroundColor = self.backRandomColor()
}
//MARK:- 轻拍手势关联方法
func tapAction(sender:UITapGestureRecognizer) {
//根据手势对象获取手势所在的视图对象
let aview = sender.view
aview?.backgroundColor = self.backRandomColor()
}
func backRandomColor() -> UIColor {
let redValue = Float(arc4random_uniform(256)) / 255.0
let greenValue = Float(arc4random_uniform(256)) / 255.0
let blueValue = Float(arc4random_uniform(256)) / 255.0
//产生随机颜色
let color = UIColor(red: CGFloat(redValue), green: CGFloat(greenValue), blue: CGFloat(blueValue), alpha: 1.0)
return color
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}