4

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!

Antoine
  • 23,526
  • 11
  • 88
  • 94

3 Answers3

3

UIButton type should be custom then setTitle works

ergunkocak
  • 3,334
  • 1
  • 32
  • 31
1

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.

Antoine
  • 23,526
  • 11
  • 88
  • 94
  • 1
    Using `setTitle` for `TARGET_INTERFACE_BUILDER` on iOS 10 / Xcode 8 beta6 didn't work for me. Instead, I was able to successfully set the button's label title, by directly accessing it's property i.e. `myButton.labelTitle?.text = myText` – flochtililoch Aug 21 '16 at 20:43
0

It now works as per Xcode 8.3.3

valeCocoa
  • 344
  • 1
  • 8