2

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.

Brandon Stillitano
  • 1,304
  • 8
  • 27

1 Answers1

2

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

enter image description here

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.

Wez
  • 10,555
  • 5
  • 49
  • 63
  • 1
    I tend to agree that swizzling is not a great approach given its uncertainty at runtime however the functionality will only be run in non production builds. I think you may be on to something though with only attempting swizzle layoutSubviews as opposed to the init. It makes life a lot easier. I’ll give it a shot and mark as approved once I’m in front of a computer. Cheers mate. – Brandon Stillitano Feb 23 '21 at 13:10
  • 1
    Can confirm that this implementation works. There are a few things on my end that I need to sort out regarding restoring previous border state on each view but this has gotten me out of the woods and onto the home stretch. For the purposes of doing what the question asked, this is 100% spot on. – Brandon Stillitano Feb 23 '21 at 23:45