Вы хотите использовать значение «index», чтобы определить, какое изображение показывать из вашего массива изображений.
Начните с 0 (ноль), чтобы показать первое изображение (массивы начинаются с нуля).
Когда вы нажимаете кнопку «Далее», увеличивает индекса и обновляет imageView (но не go сверх количества изображений в вашем массиве) .
Когда вы нажимаете кнопку «предыдущий», уменьшает индекс и обновляет imageView (но не go ниже 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]
}
}