Stranger B.
Stranger B.

Reputation: 9364

How to make a click on cell of a Table View in Swift

This is my first day in the awesome SWIFT language, I'm trying to populate a Table view with some data, everything seems to work fine, but I want to make my Table view clickable and print the id of the item clicked but it doesn't seem to be working I'm not getting any Error.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var categories = [Category]()

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return categories.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
    cell.textLabel?.text = categories[indexPath.row].Label



    return cell
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
 println("You selected cell #\(indexPath.row)!")
}



override func viewDidLoad() {
    super.viewDidLoad()


    let reposURL = NSURL(string: "http://myserver.com/file.json")
    // 2
    if let JSONData = NSData(contentsOfURL: reposURL!) {
        // 3
        if let json = NSJSONSerialization.JSONObjectWithData(JSONData, options: nil, error: nil) as? NSDictionary {
            // 4
            if let reposArray = json["List"] as? [NSDictionary] {
                // 5
                for item in reposArray {
                    categories.append(Category(json: item))
                }
            }
        }
    }
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Upvotes: 0

Views: 3481

Answers (1)

agy
agy

Reputation: 2854

It seems like you have forgotten to set your UITableViewDelegate:

override func viewDidLoad() {
  super.viewDidLoad()
  self.tableView.delegate = self

}

If you haven't defined your tableView as a variable in your code. You can define your delegate and datasource using storyboard.

storyboard

Upvotes: 1

Related Questions