Home > front end >  UIImageView slides using Buttons
UIImageView slides using Buttons

Time:10-04


I have a homework with which I'm stuck. Here it is:


Make a gallery project: a large UIImageView and two buttons below it: Back and Next. Add 10 pictures to the project, and by clicking on the buttons, the previous or next picture should be displayed, respectively.


So I made an array, and some *silly attempt* to go through this array. But i'm 100% sure that there is some simple answer to that.
Thank you!
import UIKit


class ViewController: UIViewController {
    
    @IBOutlet weak var imagesIV: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
       }
    let images = [UIImage(named: "1"), UIImage(named: "2"), UIImage(named: "3"),UIImage(named: "4"),UIImage(named: "5"),UIImage(named: "6"),UIImage(named: "7"),UIImage(named: "8"),UIImage(named: "9"),UIImage(named: "10")]
    var numberOfImages = images.count
    var  currentImage = 0

    @IBAction func forwardButton(_ sender: Any) {
        guard case currentImage   1 < images.count else {return}
        currentImage  = 1
    }
    
    @IBAction func backButton(_ sender: Any) {
    }
}

CodePudding user response:

You can try

@IBAction func forwardButton(_ sender: Any) {
    guard currentImage   1 < images.count else {return}
    currentImage  = 1
    imagesIV.image = images[currentImage]
}

@IBAction func backButton(_ sender: Any) {
    guard currentImage - 1 >= 0  else {return}
    currentImage -= 1
    imagesIV.image = images[currentImage]
}

CodePudding user response:

A better way in my opinion is below, specifically to make your code scalable (e.g. if you have 1000 photos, you don't want to add them manually one by one in the array):

class ViewController: UIViewController {
    
    @IBOutlet weak var imagesIV: UIImageView!
    var  currentImageIndex = 0
    var images : [UIImage] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        for a in 1...10 {
            if let newImage = UIImage(named: "\(a)") {
                images.append(newImage)
            }
        }
        
        updateImageInImageView()
    }
    
    @IBAction func forwardButton(_ sender: Any) {
        if currentImageIndex   1 != images.count { currentImageIndex  = 1} else { currentImageIndex = 0}
        updateImageInImageView()
    }
    
    @IBAction func backButton(_ sender: Any) {
        if currentImageIndex != 0 { currentImageIndex -= 1} else { currentImageIndex = images.count - 1}
        updateImageInImageView()
    }
    
    func updateImageInImageView()  {
        imagesIV.image = images[currentImageIndex]
    }
}
  • Related