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:
and then creating an outlet for that view like this:
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:
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With