【问题标题】:Array with images name to change my image every time i press the button in Swift每次按下 Swift 中的按钮时,带有图像名称的数组来更改我的图像
【发布时间】:2018-06-23 10:01:48
【问题描述】:

我有一个图像名称为 let arrowArray = ["up","down","right","left"] 的数组,我在我的故事板中放置了一个 imageView 和一个带有操作的按钮

我想在每次按下按钮时更改我的图像, 谁能帮帮我?

【问题讨论】:

  • 请指定您希望如何更改图像。您是否要遍历数组并在到达最后一个元素后从第一个元素重新开始?或者一旦到达最后一个元素,就停止更改图片。或者每次按下按钮时从数组中选择一个随机元素。请更具体。

标签: ios arrays swift image swift4


【解决方案1】:

感谢Xcoder的上一个回答,我已经修复了代码,所以图像不会停止

func updateImage() {

    if arrowIndex >= 0 && arrowIndex < 4 {
        arrowImage.image = UIImage(named: arrowArray[arrowIndex])
        arrowIndex += 1
        if arrowIndex == 4 {
            arrowIndex = 0
        }
    }else{
        arrowIndex = 0
    }

}


@IBAction func buttonClicked(_ sender: UIButton) {

   updateImage() 

      }

【讨论】:

    【解决方案2】:

    在您的视图控制器中:

    var arrowIndex: Int = 0
    
    @IBAction func buttonClicked(_ sender: UIButton) {
        yourImageView.image = UIImage(named: arrowArray[arrowIndex])
        arrowIndex += 1
    
        if arrayIndex == (arrowArray.count - 1) {
            arrayIndex = 0
        }    
    }
    

    这将首先显示向上箭头。您可以更改arrowIndex 的初始值以先显示不同的箭头。

    【讨论】:

    • 我遇到了崩溃!索引超出范围
    • @desperado_ah 很抱歉。检查我更新的答案,让我知道它是否适合你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2014-10-06
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 2012-05-15
    相关资源
    最近更新 更多