Chris Färber
Chris Färber

Reputation: 1

How to print by press of a button a simple quote in swift at random from an array?

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

Answers (1)

vadian
vadian

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

  • Connect (-drag) the button to the IBAction and the label to the IBOutlet
  • Run the app and press the button

Upvotes: 2

Related Questions