gpt4 book ai didi

swift - 使用字典中设置的图像名称更改 UIImage 图像属性

转载 作者:行者123 更新时间:2023-11-28 07:34:02 25 4
gpt4 key购买 nike

我正在构建一个简单的应用程序,您点击一个按钮,图像会随机变化,但我还想添加一个描述图像的标签,所以我创建了一个包含 ["fileName":"Description "] 但是当我尝试更改图像时出现错误:

"Cannot subscript a value of type '[String : String]' with an index of type 'Int'"

var randomNumber = 0
let arrayOfImages : [String:String] = ["ball1":"yes","ball2":"no","ball3":"ask again later","ball4":"the answer is yes","ball5":"i dont know"]

func rollButton() {
randomNumber = Int.random(in: 0...4)
ballImage.image = UIImage(named: arrayOfImages[randomNumber])
}

如何使用 Dictionary 更改 UIImage.image

最佳答案

替换

ballImage.image = UIImage(named: arrayOfImages[randomNumber])

ballImage.image = UIImage(named: Array(arrayOfImages.keys)[randomNumber])

因为你不能为数组下标字典,一个好的做法是创建

struct Item { 
let imageName:String
let des:String
}

let arr = [Item(imageName: "ball1", des: "con1"),Item(imageName: "ball2", des: "con2"),Item(imageName: "ball3", des: "con3")]
let ran = arr[Int.random(in: 0...2)]
ballImage.image = ran.imageName

关于swift - 使用字典中设置的图像名称更改 UIImage 图像属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53747705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com