Search code examples
iosswiftimagebutton

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. 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. I know how to write this function. But i don't know how to set the image of the button with a variable 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
}

Solution

  • 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


    So in cellForRowAt you can get certain 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)