1

In my app I'm allowing the user the change some of the UI elements based on color. So, I have three versions of an image which can be used for a button and I'd like to select the image programmatically:

PSEUDO CODE
"image0", "image1", "image3"
var userChoice:integer

myButton.setImage("myImage"+userChoice , .normal)

I've seen this solution in SO: Programmatically access image assets

What would be the Swift equivalent code?

Right now I'm using image literal:

self.But_Settings.setImage(#imageLiteral(resourceName: "settingswhite"), for: UIControlState.normal)

but of course Xcode changes this part "#imageLiteral(resourceName: "settingswhite")" to an icon which cannot be edited.

Community
  • 1
  • 1
wayneh
  • 4,393
  • 9
  • 35
  • 70

3 Answers3

3

Then don't use image literal. Image literals are just that - a hard value in code that you can't change during run time. Load an image dynamically from your bundle:

if let image = UIImage(named: "myImage" + userChoice) {
    self.But_Settings.setImage(image, for: .normal)
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
0

Do you think this would help? : But_Settings.setImage(UIImage(named: "play.png"), for: UIControlState.normal). Here you are using name of the asset

Vandan Patel
  • 1,012
  • 1
  • 12
  • 23
0

Since it's a limited number of choices it sounds like a good place for an enum.

enum ImageChoice: Int {
case zero = 0, one, two

var image: UIImage {
 switch self {
  case .zero:
   return // Some Image, can use the icon image xcode provides now
  case .one:
   return //another image
  case .two:
   return //another image
  }
 }
}

Then you can easily get the correct image by initializing the enum by using an Int value.

guard let userChoice = ImageChoice(rawValue: someInt) else { return //Default Image }
let image = userChoice.image
JustinM
  • 2,202
  • 2
  • 14
  • 24