创建两个类,First, Second.写好touches的实现方法
Paste_Image.pngimport UIKit
class SecondView: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//UIView的实现会自动往下层传递
print("second begin")
super.touchesBegan(touches, withEvent: event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("second moved")
super.touchesMoved(touches, withEvent: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("second ended")
super.touchesEnded(touches, withEvent: event)
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
print("second cancel")
super.touchesCancelled(touches, withEvent: event)
}
}
回到ViewController
import UIKit
class ViewController: UIViewController {
var rotation: CGFloat = 0
var scale: CGFloat = 1
override func viewDidLoad() {
super.viewDidLoad()
//1. 视图默认可以接收触摸事件
let firstView = FirstView(frame: CGRect(x: 100, y: 100, width: 300, height: 300))
//当父视图不能交互时,所有子视图都不能交互
//UIImageView: 默认为false,不能交互,如果上面放一个按钮,点击Button是没反应的,要更改下面这条属性为true才可以交互
// firstView.userInteractionEnabled = true
firstView.backgroundColor = UIColor.redColor()
self.view.addSubview(firstView)
//2. 视图结构不能改变事件传递顺序
let secondView = SecondView(frame: CGRect(x: 0, y: 0, width: 150, height: 150))
//用户是否可以交互
//UIView默认为true
// secondView.userInteractionEnabled = false
secondView.backgroundColor = UIColor.greenColor()
// self.view.addSubview(secondView)
firstView.addSubview(secondView)
let rotate = UIRotationGestureRecognizer(target: self, action: #selector(didRotate(_:)))
firstView.addGestureRecognizer(rotate)
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(didPinch(_:)))
firstView.addGestureRecognizer(pinch)
}
func didRotate(sender: UIRotationGestureRecognizer) {
let firstView = sender.view!
// firstView?.transform = CGAffineTransformMakeRotation(sender.rotation)
firstView.transform = CGAffineTransformRotate(firstView.transform, sender.rotation - rotation)
rotation = sender.rotation
print(sender.rotation)
if sender.state == .Ended {
rotation = 0
}
//手势每次都是从0开始
print("rotate: ", sender.rotation)
}
func didPinch(sender: UIPinchGestureRecognizer) {
let firstView = sender.view!
//??????
firstView.transform = CGAffineTransformScale(firstView.transform, sender.scale - scale + 1 , sender.scale - scale + 1)
scale = sender.scale
if sender.state == .Ended {
scale = 1
}
print("scale: ", sender.scale)
}
//设置touches开始,移动,结束,取消事件
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("ViewController begin")
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("ViewController moved")
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
print("ViewController ended")
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
print("ViewController cancel")
}
}
网友评论