Override UILabel setText: method in Swift

I have a problem that I got some crashes in iOS with a subclass of UILabel . Now, I would like to override setText: to call layoutIfNeeded , as this may solve the problem according to some stackoverflow answers ( like this one ).

But how can I achieve this? In Objective-C, this was not important, but I did not find a way to override setText: in Swift.

+6
source share
2 answers

Cancel the text property and specify the code in didSet , which will be executed when the text property is set:

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

I pulled out the Swizzling method in Swift 2.0. Moving the setText method to UILabel.

Copy the code into the application delegate and use customSetText to change the application level.

  // 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) } } 
+3
source

All Articles