UITableViewCell are reusable. This means that you must set the caption to “unlike” or “like” for each cell. The easiest way, since I assume that you will read the data anyway, would be to create an array of strings in your ViewController
Add this to your ViewController : var likes: [String]!
in ViewDidLoad: likes = [String](count: 20, repeatedValue: "like") Note that the length should be based on the number of UITableViewCells that you will show.
Your cellForRowAtIndexPath :
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as TableViewCell cell.like.tag = indexPath.row cell.like.addTarget(self, action: "handleLikes:", forControlEvents: .TouchUpInside) cell.like.setTitle(likes[indexPath.row], forState: UIControlState.Normal) return cell }
handleLikes :
func handleLikes(sender: AnyObject){ println(sender.tag) // This works, every cell returns a different number and in order. if likes[sender.tag] == "like" { likes[sender.tag] = "unlike" } else { likes[sender.tag] = "like" } sender.setTitle(likes[sender.tag], forState: UIControlState.Normal) }
source share