Jimmery
Jimmery

Reputation: 10139

Swift UITableView responding to when a user taps a cell

In the TableViewController I have this code:

override func viewDidLoad(){

    super.viewDidLoad()

    self.tab = UITableView(frame: CGRectMake(8, 80, 584, 512), style: UITableViewStyle.Plain)
    self.tab?.delegate = self
    self.tab?.dataSource = self
    self.tab?.registerClass(CustomCell.self, forCellReuseIdentifier: "cell")
    self.tab?.reloadData()

    self.view.addSubview(tab!)

}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = self.data.count {
        return count
    }
    return 0
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? CustomCell
    if cell == nil {
        cell = CustomCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "cell")
    }
    if let item = self.data[indexPath.row] as DataItem? {
        // cell.updateWithDataItem(item)
        // this line is commented out because the error occurs with or without this line
    }
    return cell
}

And in my CustomCell I have this code:

override func setSelected(selected: Bool, animated: Bool){
    super.setSelected(selected, animated: animated)
    println("cell selected \(id)")
}

When I get my JSON Data from the server, I have this code in my TableViewController which populates the table self.tab:

self.data = JSONData
dispatch_async(dispatch_get_main_queue(), {
     self.tab?.reloadData()
})

My problem is that when I populate self.tab, my UITableView, I end up with this in the console

cell selected f4324
cell selected f4325
cell selected f4326
cell selected f4327
cell selected f4328
...... and so on .....

It is as if the cells are being selected as they are added into my UITableView.

Upvotes: 3

Views: 12860

Answers (1)

Adeel Ur Rehman
Adeel Ur Rehman

Reputation: 566

Yes this is the normal behaviour of UITableView and UITableViewCell. To make it respond to the user interaction. You can implement the delegate method of UITableView:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath);

This function is called when the user tap on cell.

Upvotes: 16

Related Questions