-2

I want to change the image displayed by picking a random value from an array of images.

import UIKit

class ViewController: UIViewController {
    let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
    var number: Int = 0

    @IBOutlet weak var myImage: UIButton!

    @IBAction func buttonPressed(_ sender: UIButton) {
        number = Int.random(in: 0 ... 4)
        myImage.image = UIImage(named: imageArray[number+1])
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        myImage.image = UIImage(named: "ball1")
        number = Int.random(in: 0 ... 4)
        myImage.image = UIImage(named: imageArray[number+1])

    }
}

In lines 19, 24, and 26 (whenever I try to change the image) I get the error "Cannot assign to value: 'image is a method". Why is this?

Adam Grey
  • 95
  • 9

1 Answers1

1

Set image with state property equals to .normal:

import UIKit

class ViewController: UIViewController {
let imageArray = ["ball1", "ball2", "ball3", "ball4", "ball5"]
var number: Int = 0

@IBOutlet weak var myImage: UIButton!

@IBAction func buttonPressed(_ sender: UIButton) {
    number = Int.random(in: 0 ... 4)
    myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}

override func viewDidLoad() {
    super.viewDidLoad()
    myImage.setImage(UIImage(named: "ball1"), for: .normal)

    number = Int.random(in: 0 ... 4)
    myImage.setImage(UIImage(named: imageArray[number+1]), for: .normal)
}
}
Agisight
  • 1,778
  • 1
  • 14
  • 15