Search code examples
iosarraysswiftuiimageview

How to switch UIImages in UIViewController from Array by pressing UIButton


So I have a storyboard with UIImageView and two buttons and I need these buttons to change images in UIImageView. UIImages stored in an Array. I tried for in but it can show only only first image. Help would be appreciated :)

class ViewController: UIViewController {

var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }


// Do any additional setup after loading the view.


@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}

Solution

  • You want to use a "index" value to determine which image to show from your array of images.

    Start at 0 (zero) to show the first image (arrays are zero-based).

    When you click the "next" button, increment the index and update the imageView (but don't go beyond the number of images in your array).

    When you click the "previous" button, decrement the index and update the imageView (but don't go below 0).

    class ViewController: UIViewController {
    
        var images: [UIImage] = [
            UIImage.init(named: "2")!,
            UIImage.init(named: "3")!,
            UIImage.init(named: "4")!
        ]
    
        @IBOutlet weak var imageView: UIImageView!
    
        var imageIndex: Int = 0
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // updae the imageView with the first image
            imageView.image = images[imageIndex]
        }
    
        @IBAction func nextButton(_ sender: Any) {
            // if we're at the end of the images array, just return
            if imageIndex == images.count - 1 {
                return
            }
            // increment the index
            imageIndex += 1
            // update the image view
            imageView.image = images[imageIndex]
        }
    
        @IBAction func prevButton(_ sender: Any) {
            // if we're at the start of the images array, just return
            if imageIndex == 0 {
                return
            }
            // decrement the index
            imageIndex -= 1
            // update the image view
            imageView.image = images[imageIndex]
        }
    
    }