IBInspectable setTitle:UIButton上的forState不起作用

时间:2014-12-17 10:17:12

标签: ios swift uibutton interface-builder ibinspectable

我正在尝试使用Interface Builder中的实时渲染为UIButtons实现可本地化的类。 这是我到目前为止的代码:

@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
        }
    }

}

布局在IB中正确更新,但文本未显示。我用UILabel创建了相同的实现,它可以工作: https://github.com/AvdLee/ALLocalizableLabel

欢迎任何关于如何解决这个问题的想法!

3 个答案:

答案 0 :(得分:3)

UIButton类型应该是自定义的,然后setTitle工作

答案 1 :(得分:1)

在WWDC,我能够问一位工程师。结果以这种方式修复:

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
}

由于接口构建器针对不同的状态多次调用setTitle。

答案 2 :(得分:0)

现在按照Xcode 8.3.3

运行