mercredi 19 avril 2017

Swift 3 - Add user input to array and pick random item

The idea of this app is that the user types in something then clicks submit and the text field empties so they can type in something else then when they click a different button called randomised a label's text turns into a random item from the items the user entered. I thought I should append new inputs to an array and then create a randomIndex and then make the label's text a random item from the array using the randomIndex. Here's my code:

var choices = [""]

@IBOutlet weak var chosenLabel: UILabel!

@IBAction func randomiseButton(_ sender: Any) {
    let randomIndex = Int(arc4random_uniform(UInt32(self.choices.count)))
    let randomItem = self.choices[randomIndex]
    self.chosenLabel.text = "\(randomItem)"
}

@IBOutlet weak var enterLabel: UITextField!


@IBAction func submitButton(_ sender: Any) {
    let newItem = self.enterLabel.text
    self.choices.append(newItem!)
    self.enterLabel.text = ""
}

Thanks for all help in advance. Btw this doesn't bring up an error or anything but when I run this app on my iPad and enter things it works fine until I click randomise and then nothing happens. :(




Aucun commentaire:

Enregistrer un commentaire