Search code examples
iosxcodeuitableviewswiftdidselectrowatindexpath

My UITableView cell is not giving me the right information


I have close to 30 cells being occupied in my UITableView. I used storyboard mode to create the table. When I'm trying to call the cell that I selected its registering as 0 no matter what cell I've chosen. How do I get my cell to register the exact number I pushed and insert that into my currentTag? Here is what I have so far

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

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel?.text = catNames[indexPath.row]
        cell.textLabel?.textColor = UIColor.whiteColor()
        cell.backgroundColor = UIColor(red: 0x0e/255, green: 0x1b/255, blue: 0x35/255, alpha: 1.0)
        cell.textLabel?.textAlignment = NSTextAlignment.Left
        cell.textLabel?.lineBreakMode = NSLineBreakMode.ByTruncatingMiddle
        cell.textLabel?.adjustsFontSizeToFitWidth = true
        return cell
    }

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

        currentTag = tableView.tag
        println("This is the \(currentTag)")
        self.performSegueWithIdentifier("table2Segue", sender:self)

    }

Solution

  • NSIndexPath provides the section and row for the table view selection.

    Similarly to how you set the cell's text via catNames[indexPath.row], you should use indexPath.row to determine the index of the cell that was tapped.

    Therefore:

    currentTag = indexPath.row;