Marc Marc - 3 months ago 10
Swift Question

Change image ImageView with back button

I'm new on coding in Swift. My first project contains a set of images shown with an next button. What i need is a back button so when you are on image 3 you go back to image 2 etc. Can anybody help me? Here is the code that works fine with a next button.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

@IBOutlet weak var labelText: UILabel!

var imageList: [String] = [“Image1.png”, ”Image2.png”, ”Image3.png”]
var nameList: [String] = [“Text1”, ”Text2”, ”Text3”]

let maxImgs = 3
var imgIndex: NSInteger = 0

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

view.backgroundColor = UIColor(patternImage: UIImage(named: ”Image1”) !)

imageView.image = UIImage(named: ”Image1”)
labelText.text = nameList[0]
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.

}

@IBAction func nextButton(sender: AnyObject) {
if imgIndex > maxImgs {
imgIndex = 0
}
imageView.image = UIImage(named: imageList[imgIndex])
labelText.text = nameList[imgIndex]
imgIndex += 1

}
}

Answer

Just add this function inside your viewController

@IBAction func previousButton(sender: AnyObject) {
    if imgIndex < 0 {
        imgIndex = maxImgs
    }
    imageView.image = UIImage(named:imageList[imgIndex])
    labelText.text = nameList[imgIndex]
    imgInde-=1
}