Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating uitableview programmatically in swift not loading

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.

like image 235
user2924482 Avatar asked Sep 22 '15 04:09

user2924482


People also ask

How do I populate UITableView?

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.


3 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 will set the frame of your tableview, with default UITableViewStyle as well.

like image 72
Zigii Wong Avatar answered Sep 30 '22 16:09

Zigii Wong


late but can help others, you have to add :

tableView.translateAutoresizingMaskIntoConstraints = false
like image 35
Willy Cornejo Avatar answered Sep 30 '22 16:09

Willy Cornejo


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

like image 32
S. M. Sadrul Islam Asif Avatar answered Sep 30 '22 16:09

S. M. Sadrul Islam Asif