0

When I run this code and tap on a cell it always puts the checkmark on the bottom most cell, if I scroll the table view up and down it puts it on the top most cell. Any ideas?

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return resultsArray.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell

    if (cell != nil) {

        cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

    }

    cell?.textLabel?.text = resultsArray[indexPath.row] as? String

    return cell!

}


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

    println(indexPath.row)

    if cell?.accessoryType != UITableViewCellAccessoryType.Checkmark {

        cell?.accessoryType = UITableViewCellAccessoryType.Checkmark

    } else if cell?.accessoryType == UITableViewCellAccessoryType.Checkmark  {

        cell?.accessoryType = UITableViewCellAccessoryType.None
    }

}

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}
Fred Faust
  • 6,696
  • 4
  • 32
  • 55
  • There is a thread over here that may be of use: http://stackoverflow.com/questions/24266467/swift-tableview-cell-set-accessory-type – Steve Rosenberg Sep 30 '14 at 21:30

1 Answers1

0

Where does the cell come from in the penultimate method? You're using cell? a lot. It's supposed to be a local variable in the cellForIndex method; you look like you're defining this at the instance level instead, which explains the behaviour you are seeing.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
  • Ah ha! I am indeed declaring it as an instance variable so I can use it again in the didSelectRow method, which now leads me to think I am using it wrong. I'll look into how to do that properly, thank you. (I really wanted to run some code based on if the row was selected, which actually works fine, it was just the checkmark that was all over the place - thanks again!) – Fred Faust Sep 30 '14 at 22:14