Reputation: 9120
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.
Upvotes: 9
Views: 14023
Reputation: 1
before setting up delegates, use
tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
It will work properly
Upvotes: 0
Reputation: 342
SWIFT 3x
tableView.register(UINib(nibName: "cell", bundle: nil), forCellReuseIdentifier: "cell")
Upvotes: 0
Reputation: 1225
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.")
}
}
Upvotes: 1
Reputation: 4066
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)
}
Upvotes: 0
Reputation: 7826
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.
Upvotes: 10
Reputation: 76
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
Upvotes: 1
Reputation: 115
late but can help others, you have to add :
tableView.translateAutoresizingMaskIntoConstraints = false
Upvotes: 1