简体   繁体   中英

Random data transfer to button in Swift. (Array)

import UIKit

class ViewController: UIViewController {
    
    var buttonArray = [String] ()

    
    @IBOutlet weak var button3: UIButton!
    @IBOutlet weak var button2: UIButton!
    @IBOutlet weak var button1: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        buttonArray.append("answer1")
        buttonArray.append("answer2")
        buttonArray.append("answer3")
    }

    @IBAction func buttonClick(_ sender: UIButton) {
        while true {
            let randomArray = buttonArray[Int.random(in: 0...2)]
            button1.titleLabel?.text = randomArray
            break
        }
    }
    
}


I want to create a test. This test will have 3 answer choices and these answers will be randomly assigned to the buttons. I don't want an answer to be assigned to two choices. for this, I want to take the first assigned option into the array and remove it from the array after it is assigned. i don't understand how i can do this

You can remove an item at a random index. This item is returned from remove(at:

 let randomElement = buttonArray.remove(at: Int.random(in: 0..<buttonArray.count)]
 button1.titleLabel?.text = randomElement

Side note: Never hard-code array indices for a range.

To assign all three values randomly to the three buttons shuffle the array

let shuffledArray = buttonArray.shuffled()
button1.titleLabel?.text = shuffledArray[0]
button2.titleLabel?.text = shuffledArray[1]
button3.titleLabel?.text = shuffledArray[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM