Implementing a like button in a tableviewCell in swift

前端 未结 1 1510
-上瘾入骨i
-上瘾入骨i 2021-01-03 09:04

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

相关标签:
1条回答
  • 2021-01-03 09:35

    UITableViewCells 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)
    }
    
    0 讨论(0)
提交回复
热议问题