首页 > 解决方案 > 如何更改具有可变图像名称的按钮的图像?

问题描述

我想以编程方式更改按钮的图像。我现在唯一的方法是:

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

但现在我想使用一个变量imagename。有没有办法做到这一点?最后,我有一个图像文件夹,然后我使用函数收集图像。该函数的最后一行是我将 imagename 设置为收集的图像的名称。我知道如何编写这个函数。但我不知道如何使用变量图像名设置按钮的图像。我希望你能理解我的问题,任何人都可以帮助我。

这里的代码:

 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
}

标签: iosswiftimagebutton

解决方案


由于您有一个元素数组,因此您可以通过指定其索引来获取某个元素

array[index]
       ^ Int

...请注意,第一个元素的索引是 0,而不是 1


因此,cellForRowAt您可以UIImage?通过在索引等于当前索引路径行的数组中获取图像来确定。不要忘记打开它

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

推荐阅读