Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ryan Jin
15,337 PointsHow to add a UITableView Programmatically in a single function without using UITableViewDataSource in Swift
Can somebody tell me how to add a table view programmatically? I am having trouble finding the value for tableView.datasource, so I can't display the data. Here is my code
import UIKit
class ViewController: UIViewController{
let cellIdentifier = "Cell"
override func viewDidLoad() {
let screenSize = UIScreen.mainScreen().bounds
let screenHeight = screenSize.height
let screenWidth = screenSize.width
var tableView = UITableView(frame: (CGRectMake(0, 0, screenWidth, screenHeight)), style: UITableViewStyle.Grouped)
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier)
tableView.numberOfRowsInSection(5)
var indexPath = NSIndexPath()
let cell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as UITableViewCell
cell.textLabel!.text = "hello WOrld"
tableView.indexPathForCell(cell)
view.addSubview(tableView)
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
So I have to find what the value tableView.datasource is. I dont' want to use the protocol UITableViewDatasource, so can somebody tell me what should this value be?
1 Answer
Michael Vilabrera
Courses Plus Student 11,252 PointsYou should use the protocol, it is still applicable as 'programmatic'.