Creating a uitableview programmatically in fast boot

I am trying to create a uitableview programmatically in swift but not loading here, this 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) } 

Do any of you know what I am missing or what is wrong with my code?

I will be very grateful for your help.

+8
ios uitableview swift2
source share
7 answers
 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 sets the frame of your tableview , also the default UITableViewStyle .

+9
source share

late, but may help others, you should add:

 tableView.translateAutoresizingMaskIntoConstraints = false 
+1
source share

Try the following:

  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 configure the frame as: CGRectMake (x, y, width, height) Here the width and height refer to the desired width and height of the table.

+1
source share

SWIFT 3.x

 //MARK: Create TableView func createTableView() -> Void { print("Create Table View.") if self.tblView == nil{ self.tblView = UITableView(frame: UIScreen.main.bounds, style: .plain) self.tblView.delegate = self self.tblView.dataSource = self self.tblView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") self.view.addSubview(self.tblView) } else{ print("Table view already has been assigned.") } } 
+1
source share

before setting delegates use

 tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain) 

It will work fine

0
source share

SWIFT 3:

 var tableView: UITableView = UITableView() override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: UIScreen.main.bounds, style: .plain) tableView.delegate = self tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.view.addSubview(tableView) } 
0
source share

SWIFT 3x

 tableView.register(UINib(nibName: "cell", bundle: nil), forCellReuseIdentifier: "cell") 
0
source share

All Articles