I am trying to make a like button in each of my tableview cells. When it is pressed, the button will change to \"unlike\". I was able to do this by creating an IBOutlet in m
UITableViewCell
s are reusable. This means that you must set the title to "unlike" or "like" for each cell. Easiest way, since I suppose you will be reading in data anyways, 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 display.
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
function:
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)
}