IBInspectable setTitle:forState on UIButton not working

1.3k views Asked by At

I'm trying to implement a localizable class for UIButtons using live rendering in the Interface Builder. This is the code I have so far:

@IBDesignable class TIFLocalizableButton: UIButton {

    @IBInspectable var localizeString:String = "" {
        didSet {
            #if TARGET_INTERFACE_BUILDER
                var bundle = NSBundle(forClass: self.dynamicType)
                self.setTitle(bundle.localizedStringForKey(self.localizeString, value:"", table: nil), forState: UIControlState.Normal)
            #else
                self.setTitle(self.localizeString.localized(), forState: UIControlState.Normal)
            #endif
        }
    }

}

The layout is correctly updating in the IB, but the text isn't showing up. I've created the same implementation with UILabel's which does work: https://github.com/AvdLee/ALLocalizableLabel

Any ideas on how to fix this are welcome!

3

There are 3 answers

1
Antoine On

At WWDC I was able to ask one of the engineers. Turns out to be fixed in this way:

override func setTitle(title: String?, forState state: UIControlState) {

    #if TARGET_INTERFACE_BUILDER
        let bundle = NSBundle(forClass: self.dynamicType)
        super.setTitle(bundle.localizedStringForKey(self.localizeString, value:"", table: nil), forState: UIControlState.Normal)
    #else
        super.setTitle(title, forState: state)
    #endif
}

As the interface builder calls the setTitle multiple times for different states.

0
ergunkocak On

UIButton type should be custom then setTitle works

0
valeCocoa On

It now works as per Xcode 8.3.3