首页 > 解决方案 > Swift UI - 图片库上的按钮返回

问题描述

如何制作后退按钮?我以我想做的方式弄错了。先感谢您。

   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]
 
}

后退按钮给出错误

标签: iosswiftuikit

解决方案


您的阵列中有 5 张图像。

当您点击后退按钮时,假设i当前等于0

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

如果您希望后退按钮从 0(第一张图像)“环绕”到 4(最后一张图像),您应该这样做:

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

如果你想在第一张图片:

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

推荐阅读