#36 模仿 Google search 小遊製作 iOS App 轉盤遊戲

模仿 Google search 小遊戲製作 iOS App 的轉盤遊戲

繪製轉盤

完成版面

自訂類別

為轉盤自訂類別 WheelImageView

詳細可參考彼得潘的文章

  1. 點選File -> New -> File

2.選擇iOS Source下的Cocoa Touch Class。

3. 在Class欄位輸入類別名稱,Subclass of欄位輸入繼承的父類別名稱。

4. 產生新類別的swift檔。

轉盤的程式碼

import UIKitclass wheelImageView: UIImageView {var currentValue: Double = 0
func rotateGradually(handler:@escaping (String) -> ()) {
var result = ""
let randomDouble = Double.random(in: 0..<2 * Double.pi) // 產生0~2pi隨機的Double數字,也就是0~360度。
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
CATransaction.begin()
rotateAnimation.fromValue = currentValue
currentValue = currentValue + 100 * Double.pi + randomDouble //開始到結束之,總共了50圈加上randomDouble度。
let value = currentValue.truncatingRemainder(dividingBy: Double.pi * 2) //取得currentale/Doublepi*2餘數
let degree = value * 180 / Double.pi //將弧度轉成角度
switch degree{ //依照不同角度判斷轉到區塊
case 0..<30:
result="1"
case 30..<60:
result="2"
case 60..<90:
result="3"
case 90..<120:
result="4"
case 120..<150:
result="5"
case 150..<180:
result="6"
case 180..<210:
result="7"
case 210..<240:
result="8"
case 240..<270:
result="9"
case 270..<300:
result="10"
case 300..<330:
result="11"
case 333..<360:
result="12"
default:
result="...未知"
}
rotateAnimation.toValue = currentValue
rotateAnimation.isRemovedOnCompletion = false //動畫結束後仍保在結束狀態,讓轉盤不會在動畫結束時回到最初狀態。便繼再次轉動。
rotateAnimation.fillMode = .forwards
rotateAnimation.duration = 5 //動畫持續時間
rotateAnimation.repeatCount = 1 // 重複幾次
CATransaction.setCompletionBlock { //跑完動後要做的事
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3){//動畫結束後暫停0.3秒
handler(result)
}
}
rotateAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0, 0.9, 0.4, 1.00)//用cubic Bezier curve決定動畫速率曲線
//也可以用內建的easeOut,但我想要最後轉一點
self.layer.add(rotateAnimation, forKey: nil)
CATransaction.commit()
}
}

轉盤建立IBOutlet

轉盤圖片 Class 選擇剛剛建立的 wheelImageView

建立IBOutlet

@IBOutlet weak var wheelImageView: wheelImageView!

按鈕建立IBAction

@IBAction func startButton(_ sender: Any) {
messageLabel.text = "text"
wheelImageView.rotateGradually { resule in
let alertContoller = UIAlertController(title: "你轉到了\(resule)區塊", message: nil, preferredStyle: .alert)
let okAction = UIAlertAction(title: "確認", style: .cancel, handler: nil)
alertContoller.addAction(okAction)
self.present(alertContoller,animated: true)

}
}

動畫展示

--

--

Rose
彼得潘的 Swift iOS / Flutter App 開發教室

Coding & Design 一直在學習的路上,從未停止,一有空檔就會摸摸我的兔子🐰