Website Links

Thursday, 10 December 2015

Swift - Table views in a view controller

UITableView is a common way of displaying lists of information, this article will take you through the basics of setting one up.

Storyboard

Add a UITable view to your view controller in the storyboard, then select the button which looks like a venn diagram in the top right corner of your screen to display your code alongside the storyboard. Select the UITableView and hold down control while clicking and dragging towards the code, this will allow you to insert an IBOutlet into your view controller which can be used to reference the table view:



You will then want to select the tableview again, hold down control and drag up to this button:



And choose to make your view controller both the datasource and delegate.

View Controller

The next step is implementing UITableViewDataSource and UITableViewDelegate in your view controller:

  class SpellingListsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet var _spellingModesTableView: UITableView!
    var modes : NSMutableArray!

    ...

    // number of rows that will be in the table
    func tableView(tableView: UITableView, 
      numberOfRowsInSection section: Int) -> Int {
      
      if (modes == nil) {
        return 0
      }
        
      return modes.count
    }
    
    // deleting from core data and removing from table view
    // on delete action on cell
    func tableView(tableView: UITableView, commitEditingStyle 
      editingStyle: UITableViewCellEditingStyle, 
      forRowAtIndexPath indexPath: NSIndexPath) {
      
      if (editingStyle == UITableViewCellEditingStyle.Delete) {
        var appDelegate : AppDelegate = UIApplication
          .sharedApplication().delegate as! AppDelegate
        
        var context : NSManagedObjectContext = 
          appDelegate.managedObjectContext!
        
        context.deleteObject(modes[indexPath.row] 
          as! NSManagedObject)

        context.save(nil)
        modes.removeObjectAtIndex(indexPath.row)
        _spellingModesTableView.reloadData()
      }
    }
    
    //should use dequeueReusableCellWithIdentifier
    func tableView(tableView: UITableView, cellForRowAtIndexPath 
      indexPath: NSIndexPath) -> UITableViewCell {
        
      let cell = UITableViewCell(
        style: UITableViewCellStyle.Subtitle,
        reuseIdentifier: "mode")
        
      var mode = modes[indexPath.row] as! NSManagedObject
      cell.textLabel?.text = mode.valueForKey("name") as? String
      cell.detailTextLabel?.text = mode.valueForKey("description") 
        as? String
      cell.accessoryType = 
        UITableViewCellAccessoryType.DisclosureIndicator
        
      return cell
    }
    
    // do something with the selected row, e.g show detail
    func tableView(tableView: UITableView, 
      didSelectRowAtIndexPath indexPath: NSIndexPath) {
      ...
    }
    
    
  }

No comments:

Post a comment