ios - 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]
}
后退按钮给出错误
解决方案
您的阵列中有 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]
推荐阅读
- r - RStudio:从 URL 下载 ZIP 文件并从 ZIP 文件读取 CSV 文件时出现问题
- amazon-web-services - AWS IAM 政策 - 限制 VPC 租赁
- matlab - Matlab - 创建压缩的彩色视频
- java - 如何在已经分区的步骤中禁用块?
- xml - 如何在 xslt 转换中用新行替换给定字符?
- node.js - npm ERR ELIFECYCLE 和 ETARGET
- php - 单选按钮相互抵消,可以检查多个,并且必须只有一个
- akeneo - 通过 AKENEO PIM 的 API 获取产品组列表
- arrays - 在 Julia 中对一维数组的所有元素求和
- android - Unity 设置与 GIT 存在平台相关冲突