Search code examples
swiftoverridingextension-methodsviewcontroller

Swift: Update UIViewController insets via extension


I wanted to update the UIEdgeInsets of all my view controllers on certain devices and I wanted to see if there's a way to do it globally as an extension, rather than creating a method and calling it in viewDidLoad for each of them. Is there a way to achieve this? I tried using awakeFromNib but this doesn't work.

extension UIViewController {

    open override func awakeFromNib() {
        self.additionalSafeAreaInsets = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
    }

}

I also tried calling self.viewLayoutMarginsDidChange() after changing the edge insets, with no results.

Any suggestions would be appreciated. Am I just overriding the wrong method or is this just not possible, or as easy as I'm thinking.


Solution

  • extension UIViewController {
    
        open override func awakeAfter(using: NSCoder) -> Any? {
            self.additionalSafeAreaInsets = UIEdgeInsets(top: 100, left: 100, bottom: 100, right: 100)
            return super.awakeAfter(using: using)
        }
    
    }