如何在Swift中将两个随机生成的数字相加,然后打印出来?

6fe3ivhb  于 2022-12-17  发布在  Swift
关注(0)|答案(2)|浏览(139)

作为Swift课程的一部分,我创建了一个非常简单的应用程序,它显示2个骰子和一个按钮。每当用户按下“掷骰子”按钮时,会生成2个随机数,然后显示相应的骰子图像。
在这个小应用上我想做的改进是添加一个标签,将两个骰子的结果相加并打印结果。
例如,如果用户按下“掷骰子”按钮,一个骰子显示数字3,另一个骰子显示数字2,我希望我的标签显示这两个骰子的总和,在本例中为5。
我的代码到目前为止:

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var diceImageView1: UIImageView!
    @IBOutlet weak var diceImageView2: UIImageView!
    
    let diceArray = [
        UIImage(named: "DiceOne"),
        UIImage(named: "DiceTwo"),
        UIImage(named: "DiceThree"),
        UIImage(named: "DiceFour"),
        UIImage(named: "DiceFive"),
        UIImage(named: "DiceSix") ]
    
    @IBAction func rollButtonPressed(_ sender: UIButton) {
 
        diceImageView1.image = diceArray[Int.random(in: 0...5)]
        diceImageView2.image = diceArray[Int.random(in: 0...5)]
    
    }
    
}

我真的不知道该从何开始抱歉我是个超级新手。

lb3vh1jj

lb3vh1jj1#

let x = Int.random(in: 1...6)
let y = Int.random(in: 1...6)
let z = x + y
class ViewController: UIViewController {
    
    @IBOutlet weak var diceImageView1: UIImageView!
    @IBOutlet weak var diceImageView2: UIImageView!
    @IBOutlet weak var combinedLabel: UILabel!

    let diceArray = [
        UIImage(named: "DiceOne"),
        UIImage(named: "DiceTwo"),
        UIImage(named: "DiceThree"),
        UIImage(named: "DiceFour"),
        UIImage(named: "DiceFive"),
        UIImage(named: "DiceSix")
    ]
    
    @IBAction func rollButtonPressed(_ sender: UIButton) {
        let x = Int.random(in: 1...6)
        let y = Int.random(in: 1...6)
        let z = x + y
        diceImageView1.image = diceArray[x-1] // dice start counting at 1
        diceImageView2.image = diceArray[y-1] // array indices start at 0
        combinedLabel.text = "sum: \(z)"
    } 
}
eqqqjvef

eqqqjvef2#

你需要创建一个类似于骰子UIImageView s的UILabel(例如,名为sumLabel),然后为每个随机数分配变量:

let firstRand = Int.random(in: 1...6)
let secondRand = Int.random(in: 1...6)
let sumRand = firstRand + secondRand

然后将结果赋给rollButtonPressed()中的sumLabel.text = sumRand

相关问题