I’m attempting to swizzle the init methods of UIView and anything that subclasses it. Thus far my attempts only lead to crashes or simply do nothing noticeable.
The outcome in trying to achieve is being able to override the value of the views border colour and width in an attempt to visualise view frames without needing a debugger attached.
I've never tried swizzling before but fancied trying this out - a quick google found this article that explains how to do it with an extension
.
extension UIView {
static let classInit: Void = {
guard let originalMethod = class_getInstanceMethod(
UIView.self,
#selector(layoutSubviews)
), let swizzledMethod = class_getInstanceMethod(
UIView.self,
#selector(swizzled_layoutSubviews)
) else {
return
}
method_exchangeImplementations(originalMethod, swizzledMethod)
}()
@objc func swizzled_layoutSubviews() {
swizzled_layoutSubviews()
self.layer.borderColor = UIColor.red.cgColor
self.layer.borderWidth = 2
}
}
Then you just need to make sure you run the swizzle in your AppDelegate didFinishLaunchingWithOptions
method or somewhere at the start of your app
UIView.classInit
The above code works for me on an iOS 13.7 simulator, tho from what I have read you really should not be trying to override methods like this especially from such a core object, it'd be safer to subclass UIView
if possible.