轉吧轉吧轉吧骰子~swift

使用到random, for_in,animatedImageNamed,[UIImageView]!,motionBegan

稍微設計了一下介面,

還有更多細節想做,想用一些動態似乎要用swiftUI比較容易,

利用animatedImageNamed把6張圖變成骰子動態gif,把轉速度改成duration: 0.2 秒,看起來就可以避掉看起來笨拙的問題。

手機搖擺的motion感測有3種,
motionbegan
motionended
motioncanceled
三個的用法要再研究一下,
搖起來不太順暢…

import UIKit


class ViewController: UIViewController {



@IBOutlet var dicebtn: [UIImageView]!
@IBOutlet weak var pointText: UILabel!
@IBOutlet weak var startbtn: UIButton!
@IBOutlet weak var stopbtn: UIButton!


func diceAnimationImage(){
let animatedImage = UIImage.animatedImageNamed("dice", duration: 0.2)
dicebtn[0].image = animatedImage
dicebtn[1].image = animatedImage
dicebtn[2].image = animatedImage
dicebtn[3].image = animatedImage
dicebtn[4].image = animatedImage
dicebtn[5].image = animatedImage
pointText.text = String("?")

}

func randomdice(){
var sum = 0
for dice in dicebtn{
let dicenumner = Int.random(in: 1...6)
sum = sum + dicenumner
dice.image = UIImage(named: "dice\(dicenumner)")
pointText.text = String(Int(sum))
}
}

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.

randomdice()
stopbtn.isHidden = true


}



override func motionBegan(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if motion == .motionShake {
diceAnimationImage()
startbtn.isHidden = true
stopbtn.isHidden = false
}

}


@IBAction func playbtn(_ sender: Any) {
diceAnimationImage()
startbtn.isHidden = true
stopbtn.isHidden = false
}

@IBAction func playstop(_ sender: Any) {
startbtn.isHidden = false
stopbtn.isHidden = true
randomdice()

}

}

--

--