如何创建图像数组(swift2,xcode7)

时间:2016-07-03 15:43:05

标签: xcode swift

如果创建数组以在按下按钮时按顺序显示图像,或者在有人打开应用程序时立即自动显示图像。任何有助于解决此问题的代码。 代码

  @IBOutlet var imageview: UIImageView!

     var picture:[UIImage] = [
    UIImage(named: "page3.JPG")!,
    UIImage(named: "page4.JPG")!,
       ]

    @IBAction func buttton(sender: AnyObject) {
  }

1 个答案:

答案 0 :(得分:1)

要按顺序显示图像,代码需要另一个变量来跟踪所选图像。根据当前索引显示当前图像。按下按钮时索引会递增,并且图片会更新以使用新索引。代码还需要确保索引不超过数组中的项目数。

要在应用启动时显示图片,请在调用viewWillAppear时更新图片。

示例:

@IBOutlet var imageView: UIImageView!

// Index to keep track of the current image.
var index = 0

let picture:[UIImage] = [
    UIImage(named: "page3.JPG")!,
    UIImage(named: "page4.JPG")!,
]

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    // Update the image just before the view becomes visible, using the current image.
    imageView = picture[index]
}

@IBAction func button(sender: AnyObject) {

    // Increment the index to the next image.
    index += 1

    // If the index goes to the end of the array, then go back to the first image.
    if (index == picture.count) {
        index = 0
    }

    // Update the image view to show the current image.
    imageView.image = picture[index]
}