Atf Azi
Atf Azi

Reputation: 27

How to add and view image for next image in array by click next button

I already create an array of image (imagelateral) and I want to implement the next button in the Xcode, but I cannot view the image in the array for the next image in an array

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    let images: [UIImage] = [#imageLiteral(resourceName: "tub"),#imageLiteral(resourceName: "ball"),#imageLiteral(resourceName: "apple"),#imageLiteral(resourceName: "igloo"),#imageLiteral(resourceName: "frog")]
    var i : Int = 0
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func nextButton(_ sender: UIButton) {
        if(i+1 > images.count){
            i = 0
        }
        //self.imageView.image = [images images[i]:i]
        imageView.image = UIImage [images images[i]:i]
    }
}

it should show the next image in the array example 1st: "tub" when clicking on the button next then show "ball"

Upvotes: 0

Views: 518

Answers (2)

PGDev
PGDev

Reputation: 24341

Simply change the implementation of nextButton(_:) to,

@IBAction func nextButton(_ sender: UIButton) {
    i = (i % images.count)
    imageView.image = images[i]
    i += 1
 }

Upvotes: 0

Mehmet Salih Aslan
Mehmet Salih Aslan

Reputation: 239

There is error in nextButton action. Your array give you UIImage, you don't need create new UIImage for set your imageView. Maybe work if you change nextButton action code with following code.

@IBAction func nextButton(_ sender: UIButton) {
    i = (i+1)%images.count
    imageView.image = images[i]
}

Upvotes: 1

Related Questions