1.创建新项目Dice
2.图标
删去AppIcon,将解压后的AppIcon.appiconset文件拖入Assets包。
3.将素材点数1-6通过网页制作成2x,3x版本并拖入Asset。
4.设置对应的UI。
5.拖入Button组件并设置style。
6.Ctrl加拖拽将Button拖拽到ViewController里,并设置Connection,Name等,并点击Connect。
同样方式创建两个骰子的代码。
import UIKitclass ViewController: UIViewController {@IBOutlet weak var diceImageView1: UIImageView!@IBOutlet weak var diceImageView2: UIImageView!@IBAction func roll(_ sender: Any) {}override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}
}
7.继续编写代码创造随机数。
import UIKitclass ViewController: UIViewController {@IBOutlet weak var diceImageView1: UIImageView!@IBOutlet weak var diceImageView2: UIImageView!@IBAction func roll(_ sender: Any) {var index1: Int = Int.random(in: 1...6)var index2: Int = Int.random(in: 1...6)diceImageView1.image = UIImage(named: "dice\(index1)")diceImageView2.image = UIImage(named: "dice\(index2)") }override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}}
8.启动运行
9.程序加载时就随机扔骰子
import UIKitclass ViewController: UIViewController {let diceArr = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]@IBOutlet weak var diceImageView1: UIImageView!@IBOutlet weak var diceImageView2: UIImageView!@IBAction func roll(_ sender: Any) {//调用摇骰子函数updateDiceImages()}//当程序加载的时候的活动override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.//调用摇骰子函数updateDiceImages()}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}func updateDiceImages(){var index1: Int = Int.random(in: 0...5)var index2: Int = Int.random(in: 0...5)diceImageView1.image = UIImage(named: diceArr[index1])diceImageView2.image = UIImage(named: diceArr[index2]) }}
10.当用户摇晃骰子后调用摇骰子函数。
import UIKitclass ViewController: UIViewController {let diceArr = ["dice1", "dice2", "dice3", "dice4", "dice5", "dice6"]@IBOutlet weak var diceImageView1: UIImageView!@IBOutlet weak var diceImageView2: UIImageView!@IBAction func roll(_ sender: Any) {//调用摇骰子函数updateDiceImages()}//当程序加载的时候的活动override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.//调用摇骰子函数updateDiceImages()}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}func updateDiceImages(){var index1: Int = Int.random(in: 0...5)var index2: Int = Int.random(in: 0...5)diceImageView1.image = UIImage(named: diceArr[index1])diceImageView2.image = UIImage(named: diceArr[index2]) }//当用户摇晃手机时触发摇骰子override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {updateDiceImages()}}