今天來介紹一下iOS中相當方便的一個功能:手勢。
分別為Tap 輕點、LongPress 長按、Swipe 滑動、Pan 拖曳、Pinch 縮放及Rotation 旋轉。
首先在viewdidload()中加入以下程式碼
let tap = UITapGestureRecognizer(target: self, action: #selector(self.tap))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 1
self.views.addGestureRecognizer(tap)
self.views.addGestureRecognizer(tap)
為將這個手勢加到views中在viewdidload()中加入以下程式碼
let longpress = UILongPressGestureRecognizer(target: self, action: #selector(self.longpress))
self.views.addGestureRecognizer(longpress)
在長按後會觸發一個method
func longpress(recognizer:UILongPressGestureRecognizer){
if recognizer.state == .began{
self.views.labelS.text = "長按開始"
}else if recognizer.state == .ended{
self.views.labelS.text = "長按結束"
}
}
在viewdidload()中加入以下程式碼
let swipeUp = UISwipeGestureRecognizer(target: self, action: #selector(VC.swipe))
swipeUp.direction = .up
self.myUIView.addGestureRecognizer(swipeUp)
.up
、.down
、.right
、.left
。在觸發的method swipe中會有一個傳入值UISwipeGestureRecognizer
也會有一個參數direction
可以來確認滑動之方向。
在viewdidload()中加入以下程式碼
let pan = UIPanGestureRecognizer(target: self, action: #selector(VC.pan))
pan.minimumNumberOfTouches = 1
pan.maximumNumberOfTouches = 1
self.myUIView.addGestureRecognizer(pan)
在觸發的method pan中會有一個傳入值UIPanGestureRecognizer
會有一個參數.location
可以來確認拖曳的位置。
在viewdidload()中加入以下程式碼
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(VC.pinch))
self.views.addGestureRecognizer(pinch)
在觸發的method pan中傳入值UIPanGestureRecognizer
的參數:
.changed
、.began
、.ended
在viewdidload()中加入以下程式碼
let rotation = UIRotationGestureRecognizer(target: self, action: #selector(VC.rotation))
self.views.addGestureRecognizer(rotation)
在觸發的method pan中傳入值UIPanGestureRecognizer
的參數rotation
為旋轉的弧度。