Motivation gym5 Motivation gym5 - 5 months ago 29
Swift Question

How to create an array of images (swift2, xcode7)

How to create an array to display the images in sequence whenever the button is pressed or automatically as soon as someone opens the application.Any code which could help in solving this problem.
code below

@IBOutlet var imageview: UIImageView!

var picture:[UIImage] = [
UIImage(named: "page3.JPG")!,
UIImage(named: "page4.JPG")!,
]

@IBAction func buttton(sender: AnyObject) {
}

Answer

To display images in a sequence, the code needs another variable to keep track of the selected image. The current image is displayed according to the current index. The index is incremented when the button is pressed, and the picture is updated to use the new index. The code also needs to ensure that the index does not exceed the number of items in the array.

To display an image when the app launches, update the image when viewWillAppear is called.

Example:

@IBOutlet var imageView: UIImageView!

// Index to keep track of the current image.
var index = 0

let picture:[UIImage] = [
    UIImage(named: "page3.JPG")!,
    UIImage(named: "page4.JPG")!,
]

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // Update the image just before the view becomes visible, using the current image.
    imageView = picture[index]
}

@IBAction func button(sender: AnyObject) {

    // Increment the index to the next image.
    index += 1

    // If the index goes to the end of the array, then go back to the first image.
    if (index == picture.count) {
        index = 0
    }

    // Update the image view to show the current image.
    imageView.image = picture[index]
}