Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add reusable custom views programmatically? (Swift)

I've created a reusable xib file that contains a table and it's being loaded in a TableView.swift file like this:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)    
    Bundle.main.loadNibNamed("TableView", owner: self, options: nil)
}

I'm only mentioning this to clarify that I am not confused about how to load the xib file


I can easily load the reusable view in my RootViewController.swift file by adding a view to the UIViewController and giving that view a custom class like this:

enter image description here

and then creating an outlet for that view like this:

enter image description here

So here is my question:

Why am I not able to simply add the view like this:

let tableViewView = TableView()

When I do, I get an error that I don't totally understand:

enter image description here

like image 512
John R Perry Avatar asked May 01 '17 20:05

John R Perry


People also ask

How do I create a view programmatically in Swift?

Creating Custom Views programatically Open Xcode ▸ File ▸ New ▸ File ▸ Cocoa Touch class ▸ Add your class name ▸ Select UIView or subclass of UIView under Subclass of ▸ Select language ▸ Next ▸ Select target ▸ Create the source file under your project directory.

What is UIView in Swift?

The UIView class is a concrete class that you can instantiate and use to display a fixed background color. You can also subclass it to draw more sophisticated content.


1 Answers

You need to override the frame initializer as well.

Assuming your TableView class is a UITableView subclass, it should look something like this:

class TableView: UITableView {

    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        // any additional setup code
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        // any additional setup code
    }

}

Because you are trying to instantiate the table view programmatically, you need to give it an initializer for the frame, not only an initializer with a coder.

like image 196
nathangitter Avatar answered Sep 28 '22 09:09

nathangitter