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.

3
  • Do you think this would help? : But_Settings.setImage(UIImage(named: "play.png"), for: UIControlState.normal). Here you are using name of the asset. Commented Feb 18, 2017 at 21:41
  • @VandanPatel - Yes, that does help. I wish you had given it as an answer so I could credit you. Nevertheless, thanks. Commented Feb 19, 2017 at 0:43
  • I just did that. lol Commented Feb 19, 2017 at 1:17

3 Answers 3

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes! and DUH! Thanks
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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.