Reputation: 1
I am completely new to coding.
I started using this app called MIMO and learned a few bits and pieces. In one chapter they let us code a simple "dice app" where by pressing a button a number from 1 - 6 appears. Now I wanted to rewrite that so that at the button press the app displays a quote from a predetermined array.
I am completely stuck, however.
Here's what I got:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!"]
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
print(array[randomIndex])
override func viewDidLoad() {
super.viewDidLoad()
}
}
Upvotes: 0
Views: 89
Reputation: 285190
Basically any arbitrary code must be run in a method, in this case in an IBAction
which is triggered when the button is pressed. The method viewDidLoad
is not needed.
Change the code to
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var quotesLabel: UILabel!
let quotes = ["Quote1!", "Quote2!", "Quote3!", "Quote4!"]
@IBAction func showRandomQuote(_ sender : UIButton) {
let randomIndex = Int(arc4random_uniform(UInt32(quotes.count)))
let randomQuote = quotes[randomIndex]
quotesLabel.text = randomQuote
}
}
In Interface Builder drag a button into the canvas of the view controller
IBAction
and the label to the IBOutlet
Upvotes: 2