50天iOS挑戰(Swift) - 第2天:手勢操控彈性按鈕
50天,每天一個Swift語言的iOS練手項目,覆蓋iOS開發的主要知識。貴在堅持,重在思考
文章列表:http://blog.csdn.net/b735098742/article/category/6978601
Github項目:https://github.com/Minecodecraft/50DaysOfSwift
簡介
本項目爲製作一個可手勢操作的按鈕,支持修改顏色、手勢放大縮小、點擊切換等操作,並對按鈕添加彈性正反饋。
主要知識點: Animation、Layer、Button、UIGestureRecongnizer
過程
1、 界面UI
首先是對iOS圖層基礎使用的練習。使用代碼設計背景,這裏用到了CAGradientLayer來創建漸變圖層。
let backgroundLayer = CAGradientLayer()
backgroundLayer.colors = [UIColor.yellow.cgColor, UIColor.white.cgColor]
backgroundLayer.startPoint = CGPoint(x: 0.5, y: 0)
backgroundLayer.endPoint = CGPoint(x: 0.5, y: 1)
backgroundLayer.frame = self.view.bounds
self.view.layer.addSublayer(backgroundLayer)
添加子圖層使用layer屬性的addSublayer()方法
2、 手勢操作
這裏簡單介紹手勢操作對應的類,具體使用方法後面專開文章講解。
- 點擊手勢:UITapGestureRecognizer
- 長按手勢:UILongPressGestureRecognizer
- 拖拽手勢:UIPanGestureRecognizer
- 捏合手勢:UIPinchGestureRecognizer
- 旋轉手勢:UIRotationGestureRecognizer
- 滑動手勢:UISwipeGestureRecognizer
其中捏合、旋轉手勢需要遵守UIGestureRecognizerDelegate代理類
3、 響應手勢的動畫
1) 控件旋轉抖動
通過設置動畫過程來實現
let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
// 週期
animation.duration = 0.08
animation.repeatCount = 2
// 抖動幅度
animation.values = [0, -self.mainButton.frame.width/4, self.mainButton.frame.width/4, 0]
// 恢復原樣
animation.autoreverses = true
// 設置抖動中心
self.mainButton.layer.add(animation, forKey: "rotation.x")
2) 控件抖動
控件抖動通過設置動畫過程來實現:
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
// 週期
animation.duration = 0.08
animation.repeatCount = 4
// 抖動角度
animation.fromValue = (-M_1_PI)
animation.toValue = (M_1_PI)
// 恢復原樣
animation.autoreverses = true
// 設置抖動中心
self.mainButton.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
self.mainButton.layer.add(animation, forKey: "rotation.z")
3) 控件拖動
控件拖動通過獲取點擊起點和位移終點,並計算相對位移量實現。
注意,translation函數是獲取起點,而location函數是獲取終點。起初仿照油管上一個作者的做法利用location來實現,會導致開始單擊時出現一個跳變的位置。所以拖動位置的計算是要用起點計算相對位移的方式來實現的。
// 獲取座標並修改
let movePoint = panGes.translation(in: self.view)
var curPoint = self.mainButton.center
curPoint.x += movePoint.x
curPoint.y += movePoint.y
self.mainButton.center = curPoint
4) 控件旋轉
添加手勢
let rotationGes = UIRotationGestureRecognizer(target: self, action: #selector(rotationAction(_:)))
rotationGes.delegate = self
self.mainButton.addGestureRecognizer(rotationGes)
添加手勢後處理:
let rotationR = rotationGes.rotation
self.mainButton.transform = self.mainButton.transform.rotated(by: rotationR)
即可完成旋轉操作
5) 控件縮放
控件縮放則是利用手勢監視器的比例屬性來進行比例變化,從而變化大小,代碼很簡單。
let pinchScale = pinchGes.scale
self.mainButton.transform = self.mainButton.transform.scaledBy(x: pinchScale, y: pinchScale);
一點小小的補充
1.默認情況是不能同時進行旋轉和縮放操作的,但是這樣又很炫。讓UIGestureRecognizerDelegate的對應方法返回真,即可允許同時響應多個手勢。
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
2.項目源碼地址 GitHub,歡迎大家前來支持,希望可以隨手留個Star。多謝~