How to automatiaclly load view from parent XIB file in UIViewController subclass?

49 Views Asked by At

Assume SomeViewController being a subclass of BaseViewController.

Calling BaseViewController() automatically loads the view from BaseViewController.xib.

Calling SomeViewController() will automatically look for SomeViewController.xib and will fail if this file is not available.

Of course one could use SomeViewController(nibName: "BaseViewController", bundle: nil)) but this is not very handy.

Is there some way to automatically fall back to the parents XIB file if there is not XIB file for the child class?

1

There are 1 best solutions below

0
Dicka On
import UIKit

class BaseViewController: UIViewController {
    // Your code for BaseViewController
}

class SomeViewController: BaseViewController {
    convenience init() {
        // Attempt to load the XIB file for SomeViewController
        if let nibName = NSStringFromClass(self).components(separatedBy: ".").last {
            if Bundle.main.path(forResource: nibName, ofType: "nib") != nil {
                self.init(nibName: nibName, bundle: nil)
            } else {
                // If SomeViewController.xib doesn't exist, fallback to BaseViewController.xib
                self.init(nibName: "BaseViewController", bundle: nil)
            }
        } else {
            // Fallback to BaseViewController.xib if there's an issue with the class name
            self.init(nibName: "BaseViewController", bundle: nil)
        }
    }
}

There isn't a built-in mechanism in UIKit that automatically falls back to a parent's XIB file if a child's XIB file is missing. When you create an instance of a view controller, it will look for a XIB file with the same name as the class by default.