使用后退按钮更改图像ImageView

时间:2016-08-10 07:00:24

标签: swift

我在Swift编写新代码。我的第一个项目包含一组带有下一个按钮的图像。我需要的是一个后退按钮,所以当你在图像3上时,你会回到图像2等。有人可以帮助我吗?这是下一个按钮可以正常工作的代码。

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var labelText: UILabel!

    var imageList: [String] = [“Image1.png”, ”Image2.png”, ”Image3.png”]
    var nameList: [String] = [“Text1”, ”Text2”, ”Text3”]

    let maxImgs = 3
    var imgIndex: NSInteger = 0

    override func viewDidLoad() {
        super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

        view.backgroundColor = UIColor(patternImage: UIImage(named: ”Image1”) !)

        imageView.image = UIImage(named: ”Image1”)
        labelText.text = nameList[0]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.

    }

    @IBAction func nextButton(sender: AnyObject) {
        if imgIndex > maxImgs {
            imgIndex = 0
        }
        imageView.image = UIImage(named: imageList[imgIndex])
        labelText.text = nameList[imgIndex]
        imgIndex += 1

    }
}

3 个答案:

答案 0 :(得分:1)

你可以这样做:

let images:[UIImage] = [UIImage(named: "Image1.png"),UIImage(named: "Image2.png"),UIImage(named: "Image3.png")]
var index:Int = 0

在前进按钮上:

if(index < images.count){
    index = index + 1
    imageView.image = images[index]
}

在后退按钮上:

if(index >= 0){
    index = index - 1
    imageView.image = images[index]
}

停在最后一张图片上:

index = 0index = images.count

时停用按钮

或者您可以像这样使用自己的代码:

@IBAction func previousButton(sender: AnyObject) {
    if imgIndex == 0 {
        imgIndex = maxImgs
    }
    imgIndex -= 1
    imageView.image = UIImage(named:imageList[imgIndex])
    labelText.text = nameList[imgIndex]
}

答案 1 :(得分:0)

这与你的nextButton功能几乎相同......反过来说:)

@IBAction func previousButton(sender: AnyObject) {
    if imgIndex == 0 {
        imgIndex = maxImgs
    }
    imgIndex -= 1
    imageView.image = UIImage(named:imageList[imgIndex])
    labelText.text = nameList[imgIndex]
}

首先,通过检查索引是否为0,确保不会“超越边缘”。如果是,则将其设置为maxImgs(即3)

然后将imgIndex值减1,然后可以使用它来从各种数组中获取先前的图像。

希望对你有所帮助。

答案 2 :(得分:0)

只需在viewController

中添加此功能即可
@IBAction func previousButton(sender: AnyObject) {
    if imgIndex < 0 {
        imgIndex = maxImgs
    }
    imageView.image = UIImage(named:imageList[imgIndex])
    labelText.text = nameList[imgIndex]
    imgInde-=1
}