Как переключить UIImages в UIViewController из массива, нажав UIButton - PullRequest
0 голосов
/ 19 февраля 2020

Итак, у меня есть раскадровка с UIImageView и двумя кнопками, и мне нужны эти кнопки для изменения изображений в UIImageView. UIImages хранятся в массиве. Я попытался, но он может показать только только первое изображение. Была бы признательна за помощь:)

класс ViewController: UIViewController {

var images: [UIImage] = [
UIImage.init(named: "2")!,
UIImage.init(named: "3")!,
UIImage.init(named: "4")!]

override func viewDidLoad() {
    super.viewDidLoad() }


// Do any additional setup after loading the view.


@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any){
    for el in images {
        imageView.image = el }
}}

Ответы [ 3 ]

1 голос
/ 19 февраля 2020

Из-за l oop в вашем @IBAction вы видите только последнее изображение, установленное для вашего изображения. для решения вы можете определить переменную, с помощью действия кнопки увеличить значение и установить его в индекс массива для отображения в представлении изображения.

0 голосов
/ 19 февраля 2020

Вы хотите использовать значение «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]
    }

}
0 голосов
/ 19 февраля 2020
var images = [UIImage(named: "2"), UIImage(named: "3"), UIImage(named: "4")]
var actualImage = 0 // counter to know witch image is displayed

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBOutlet weak var imageView: UIImageView!

@IBAction func nextButton(_ sender: Any) {
    imageView.image = images[actualImage]

    if actualImage == images.count - 1 { // check if i'm at the last picture
        actualImage = 0 // reset the counter to the first position
    } else {
        actualImage += 1
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...