在Swift中覆盖UILabel setText:方法

时间:2015-10-06 03:18:22

标签: swift ios7 uilabel

我确实遇到了问题,我在iOS中遇到了UILabel子类的崩溃问题。现在我想覆盖setText:来调用layoutIfNeeded,因为这可以根据一些stackoverflow-answers(e.g. this one)来解决问题。

但我怎样才能做到这一点?在Objective-C中没什么大不了的,但我找不到在Swift中覆盖setText:的方法。

2 个答案:

答案 0 :(得分:12)

重写属性text并提供didSet中的代码,该代码将在设置text属性时执行:

class MyLabel: UILabel {
     override public var text: String? {
        didSet {
            layoutIfNeeded()
        }
    }
}

答案 1 :(得分:3)

我在Swift 2.0中提取了Method Swizzling。过了UILabel的setText方法。

复制app delegate中的代码并使用customSetText进行应用程序级别更改

   // MARK: - Method Swizzling

extension UILabel {
    public override class func initialize() {
        struct Static {
            static var token: dispatch_once_t = 0
        }

        // make sure this isn't a subclass
        if self !== UILabel.self {
            return
        }

        dispatch_once(&Static.token) {
            let originalSelector = Selector("setText:")
            let swizzledSelector = Selector("customSetText:")

            let originalMethod = class_getInstanceMethod(self, originalSelector)
            let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)

            let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))

            if didAddMethod {
                class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
            } else {
                method_exchangeImplementations(originalMethod, swizzledMethod)
            }
        }
    }

    // MARK: - Custom set text method for UI Label

    func customSetText(text: String) {
        self.customSetText(text)
        //set custom font to all the labels maintaining the size UILabel
        self.font = UIFont(name: "Lato-LightItalic", size: self.font.pointSize)
    }
}