I'm trying to create a uitableview programmatically in swift but is not loading here is my code:
class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
var tableView: UITableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)
}
Any of you knows what I'm missing or what is wrong with my code?
I'll really appreciate your help.
There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)
}
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
This line of code will set the frame of your tableview
, with default UITableViewStyle
as well.
late but can help others, you have to add :
tableView.translateAutoresizingMaskIntoConstraints = false
Try this:
override func viewDidLoad() {
super.viewDidLoad()
let screenSize:CGRect = UIScreen.mainScreen().bounds
tableView.frame = CGRectMake(0, 0, screenSize.width, screenSize.height)
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)
}
You can give customize frame as: CGRectMake(x,y,width,height) Here width and height refers to desired tableview width & height
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