Reputation: 131
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. :(
Upvotes: 1
Views: 863
Reputation: 131
Ok, so this is quite embarrassing. I tried out other people's comments and none were working. @pdil said, "Is the randomise button properly connected to the IBAction?". I added a print function into that button and nothing was working so I knew the connection was wrong. It turned out I had my button hooked up to a label. I will put here the code I used in the end:
var choices = [String]()
@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)"
print("testing")
}
@IBOutlet weak var enterLabel: UITextField!
@IBAction func submitButton(_ sender: Any) {
let newItem = self.enterLabel.text
self.choices.append(newItem!)
self.enterLabel.text = ""
}
Sorry about this and thanks for all your help :)
Upvotes: 1