ranesr/SwiftIcons

Using setIcon with no icon (at the moment attempt to set icon to nil results in crash)

vitalii-tym opened this issue · 2 comments

It might sound counterintuitive, but I wanted to use setIcon() to set a normal button title, with no icon at all.

Why I was trying to do this? I have a button, which changes its state - one of the states has icon and another doesn't have it. I simply wanted to have cleaner code like this:

    enum ButtonState {
        case gift, cancel
    }
    
    private func updateButton(state: ButtonState) {
        self.buyGiftButton.setIcon(prefixText: "", prefixTextFont: myFont,
            icon: state == .gift ? .fontAwesome(.gift) : nil,
            postfixText: state == .gift ? " Buy as a gift" : "Cancel", postfixTextFont: myFont, postfixTextColor: .white,
            backgroundColor: myColor, forState: .normal, iconSize: 20)
    }

But it looks like the icon is force-unwrapped in there and this is not possible. Instead I had to make if-else and do .setAttributedTitle for that button.

It would be good if icon was really handled as an optional in setIcon (feature request).

Hi, I found a little trick to achieve what you want. Maybe it doesn't the best option, but it works, until the author make the implementations of your request.

If you want remove icon from a button, you can do next:

button.setIcons(icons: [], forState: .normal) //this line remove all icons from uiview

Good look and best regards!

Hello, @juanm4 , thank you for your finding.
However, while checking your suggestion I found that this bug was in fact fixed in commit 200b3f2.