Search code examples
iosswiftuikit

Swift UI - Button back on image gallery


How do I make a back button? I get it wrong the way I want to do it. Thank you in advance.

   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) {
    i = (i+1)%images.count
       imageView.image = images[i]
}
@IBAction func backButton(_ sender: UIButton) {
          i = (i-1)%images.count
          imageView.image = images[i]
 
}

the back button gives an error


Solution

  • You have 5 images in your array.

    When you tap your Back button, suppose i is currently equal to 0:

    (i-1) == -1
    -1 % 5 == -1
    imageView.image = images[-1] // is invalid... there is no array index of -1 
    

    If you want the Back button to "wrap around" from 0 (the first image) to 4 (the last image), you should do:

    i -= 1
    if i < 0 {
        i = images.count - 1
    }
    imageView.image = images[i]
    

    If you want to stop at the first image:

    i = max(i - 1, 0)
    imageView.image = images[i]