简体   繁体   English

如何使用可变的图像名称更改按钮的图像?

[英]How to change image of a button with variable image name?

I want to change the image of a button programmatically. 我想以编程方式更改按钮的图像。 The only way I now is this: 我现在唯一的方法是:

button.setImage(UIImage.init(named: "imagename", for: .normal))

But now i want to use a variable imagename . 但是现在我想使用一个可变的imagename Is there any way to do this? 有什么办法吗? In the end i have a folder of images and than i collect a image with using a function. 最后,我有一个图像文件夹,然后我使用一个功能来收集图像。 The last row of the function is that i set the imagename to the name of the collected image. 函数的最后一行是我将imagename设置为所收集图像的名称。 I know how to write this function. 我知道如何编写此函数。 But i don't know how to set the image of the button with a variable imagename. 但是我不知道如何使用变量imagename设置按钮的图像。 I hope you understand my problem and anybody can help me. 希望您能理解我的问题,任何人都可以帮助我。

Here the code: 这里的代码:

 var imageArroy = [UIImage(named:"car1"),UIImage(named:"car2")]

//scrollview
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return imageArroy.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCollectionViewCell", for: indexPath) as! ImageCollectionViewCell

    var imagename: String = imageArroy[indexPath.row])

    cell.car.setImage(UIImage.init(named: imagename)!, for: .normal)

    return cell
}

Since you have an array of elements, you can get certain element by specifing its index 由于您有一个元素数组,因此可以通过指定其索引来获取某些元素

array[index]
       ^ Int

... note that index of first element is 0, not 1 ...请注意,第一个元素的索引为0,而不是1


So in cellForRowAt you can get certain UIImage? 因此,在cellForRowAt您可以获得某些UIImage? by getting image from your array on index equal to row of current index path. 通过从数组中获取与当前索引路径的行相等的索引的图像。 Don't forget to unwrap it 别忘了拆开它

cell.car.setImage(imageArroy[indexPath.row]!, for: .normal)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM