創(chuàng)建兩個類,F(xiàn)irst, Second.寫好touches的實現(xiàn)方法
Paste_Image.png
import UIKit
class SecondView: UIView {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//UIView的實現(xiàn)會自動往下層傳遞
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))
//當(dāng)父視圖不能交互時澜掩,所有子視圖都不能交互
//UIImageView: 默認為false肠缨,不能交互次氨,如果上面放一個按鈕挚币,點擊Button是沒反應(yīng)的鸵熟,要更改下面這條屬性為true才可以交互
// firstView.userInteractionEnabled = true
firstView.backgroundColor = UIColor.redColor()
self.view.addSubview(firstView)
//2. 視圖結(jié)構(gòu)不能改變事件傳遞順序
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)
}
//設(shè)置touches開始副编,移動,結(jié)束流强,取消事件
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")
}
}