Reputation: 1854
I have named a set of images like this:
Unselected:
nameOfTheImage
Selected:
nameOfTheImage~
In order to change the background image of a button, my code is written to take the string of the background image's name, and either append or take off the "~
" to change it to the correct image.
So I tried this:
let backgroundString = String(selector.currentBackgroundImage!)
print(backgroundString)
But I get this:
<UIImage: 0x146d98b80>, {485, 300}
Is there any way to get the plain name of the background image?
Any help is greatly appreciated.
Upvotes: 1
Views: 2067
Reputation: 21
I was able to retrieve the button's background image name by doing the following:
let imgDesc : String = button.currentBackgroundImage!.description
The above string (imgDesc) always contains something similar to the following:
<UIImage:0x281646400 named(main: userBike) {40, 63}>
Using prefix I drop everything after the close parenthesis in a new string variable:
var imgName = imgDesc.prefix { $0 != ")" } //always contains only one close parenthesis
Using range I retrieve the index of where "(main: " is located within my imgName variable:
let index = imgName.range(of: "(main: ")?.upperBound //always contains open parenthesis followed by main:<space>
Using the index from above I drop everything before it:
imgName = imgName.suffix(from: index!)
This ultimately isolates the image name from button.currentBackgroundImage.description:
print(imgName) //prints userBike
Prints "userBike" which is the image name successfully isolated from imgDesc.
Upvotes: 1
Reputation: 11
I just dealt with a somewhat similar problem. You can use: buttonName.setBackgroundImage(#imageLiteral(resourceName: "backgroundImageName"), for: .normal)
Where here .normal is the state of the button, so you can adjust your state accordingly.
For anyone else who might be having this problem, this is for Swift5.
Upvotes: 1
Reputation: 104
i had a similar problem. Fortunately I know the state of the button when the viewcontroller is displayed, so I created a String control, which was something like this:
var buttonState = "not selected"
then when the user clicks on the button I check:
if (buttonState == "not selected") {
// change buttonState to "selected"
// change the image of the button
}
Upvotes: 2