Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let a UIViewController to inherits another UIViewController IBOutlets?

After Implementing the following (Class Inheritance):

class UIViewControllerA: UIViewControllerB {
}

How to let UIViewControllerA to inherits UIViewControllerB IBOutlets? How can I connect the components at Storyboard to the subclass UIViewControllerA?

like image 267
keen Avatar asked Mar 10 '23 15:03

keen


1 Answers

If your goal is to let IBOutlets to be inherited, you should do the following:

1- Add the IBOutlets in the Super Class:

Super class (UIViewController) should not be directly connected to any ViewController at the storyboard, it should be generic. When adding the IBOutlets to the super class, they should not be connected to any component, sub classes should do that. Also, you might want to do some work (that's why you should apply this mechanism) for the IBOutlets in the super class.

Super Class should be similar to:

class SuperViewController: UIViewController, UITableViewDataSource {
    //MARK:- IBOutlets
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // setting text to the label
        label.text = "Hello"

        // conforming to table view data source
        tableView.dataSource = self
    }

    // handling the data source for the tableView
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

        cell?.textLabel?.text = "Hello!"

        return cell!
    }
}

2- Inherit Super Class and Connect the IBOutlets:

Simply, your sub class should be similar to:

class ViewController: SuperViewController {
    override func viewDidLoad() {
        // calling the super class version
        super.viewDidLoad()
    }
}

From storyboard, assign the view controller to ViewController (Sub Class), then rebuild the project (cmd + b).

Now, after selecting the desired View Controller and selecting "Connection Inspector", you should see -in the IBOutlets section-:

enter image description here

you can manually connect them to the UI components that exists in your sub class ViewController (drag from the empty circle to the component). they should look like:

enter image description here

And that's it! Your sub class's table view and label should inherit what's included in the super class.

Hope this helped.

like image 163
Ahmad F Avatar answered Mar 22 '23 23:03

Ahmad F