xNightxOwl
xNightxOwl

Reputation: 538

How to add items to UITableView using Swift?

i have been busting my brain trying to figure out how this works, but i can't seem to get it. i have tried using other tutorials, but with the many beta releases, everything keeps changing. i am fairly new to IOS development, so i'm kind of struggling.

in storyboard i have UITableView, which contains a cell with the identifier "myCell".

here's what i have so far. when i run the IOS simulator, nothing is presented on the table view.

any suggestions on how to fix this?

class ViewController: UITableViewController {
  override func viewDidLoad() {
      super.viewDidLoad()
  }
  override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
  }
  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
     var cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath) as UITableViewCell
     cell.textLabel?.text = "Cell #: \(indexPath.row)" // display the row number
     return cell
  }
  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
     return 10; // testing out with 10 cells
  }
}

Upvotes: 2

Views: 2049

Answers (1)

jamespick
jamespick

Reputation: 1978

Add the function

optional func numberOfSectionsInTableView(tableView: UITableView) -> Int

and return the number of sections you want.

You should make sure in the storyboard your UITableViewController has the class ViewController like so:

enter image description here

and that ViewController is both the delegate and datasource of the UITableViewController like so (Referencing Outlets):

enter image description here

You should also check that your UITableViewController is set to initialViewController if you don't see any lines at all (check the one at the bottom).

enter image description here

Upvotes: 4

Related Questions