JGuizard
10/9/2015 - 8:55 AM

TableView delegate and datasource class example

TableView delegate and datasource class example

import Foundation
import UIKit

class TableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource
{
    var CLASS_TAG="TableViewController"

    @IBOutlet weak var tableView: UITableView!
    var exercises: NSMutableArray = []
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        NSLog(CLASS_TAG+": viewDidLoad()")
        self.tableView.delegate=self
        self.tableView.dataSource = self
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int
    {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        NSLog("Count: "+String(exercises.count))
        return exercises.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        NSLog("Table entry")
        
        let cell = self.tableView.dequeueReusableCellWithIdentifier("ExerciseCell", forIndexPath: indexPath) as! ExerciseCell
        let row = indexPath.row
        let entry = exercises.objectAtIndex(row) as! Exercise
        NSLog(entry.getName())
        cell.tvExercise.text = entry.getName()
        cell.tvInfo.text=String(entry.getSeries())+" sets - "+String(entry.getTime())+" seconds"
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        NSLog("On click")
        let exercise=exercises.objectAtIndex(indexPath.row) as! Exercise
        NSLog(exercise.getName())
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("ExerciseController") as! ExerciseController
        vc.exercise=exercise
        self.presentViewController(vc, animated: true, completion: nil)
    }
}

/*
import Foundation
import UIKit

class ItemCell : UITableViewCell
{
    @IBOutlet weak var tvItem: UILabel!
    @IBOutlet weak var imgItem: UIImageView!
}
*/