1

I'm trying to create a simple application. There should be an image (1 of 3 images) on the screen and a button CHANGE IMAGE. array contains 3 images, included in the project (1.jpg, 2.jpg, 3.jpg)

if statement check returns us back to 1st element of array.

Could someone please help me to solve this problem? http://prntscr.com/jc6wti

import UIKit

class ViewController: UIViewController {
    var array : [UIImage] = []
    var index = 0

    @IBOutlet weak var imageOutlet: UIImageView!

    @IBAction func buttonAction(_ sender: Any) {
        imageOutlet.image = array[index]
        index += 1
        if index >= array.count {
            index = 0
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let image1 = UIImage(named: "1.jpg")
        let image2 = UIImage(named: "2.jpg")
        let image3 = UIImage(named: "3.jpg")

        array = [image1!, image2!, image3!]

        imageOutlet.image = array[index]
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • I would, at the very least, verify that `image1`, `image2` and `image3` are not optionals before you forcefully unwrap them – MadProgrammer May 01 '18 at 01:03
  • add the images to `Assets.xcassets` and initialize your images like this: `UIImage(named: "1")` without the `.jpg` – Nader May 01 '18 at 01:26
  • The reason is that at least one of your image is nil. Make sure your images has jpg not JPG – Dmitry May 01 '18 at 01:48

0 Answers0