每个TableView单元更新,而不是只是一个被点击。

我有两个button(喜欢/不喜欢),像大拇指上下投票系统风格。 当我点击button时,每个单元格都被更新。 有没有办法解决这个问题,只有被点击的人更新?

另外,如何重新加载单元格,以便我不必刷新刷新以更新button.setTitle值的值?

这是我的代码:

PFTableViewCell: class UserFeedCell: PFTableViewCell { @IBOutlet weak var likeButton: UIButton! @IBOutlet weak var dislikeButton: UIButton! var vote: Int = 0 // initialize to user's existing vote, retrieved from the server var likeCount: Int = 0 // initialize to existing like count, retrieved from the server var dislikeCount: Int = 0 // initialize to existing dislike count, retrieved from the server @IBAction func dislikeButton(sender: UIButton) { buttonWasClickedForVote(-1) print(likeCount) print(dislikeCount) 

}

 @IBAction func likeButton(sender: UIButton) { buttonWasClickedForVote(1) print(likeCount) print(dislikeCount) 

}

 private func buttonWasClickedForVote(buttonVote: Int) { if buttonVote == vote { // User wants to undo her existing vote. applyChange(-1, toCountForVote: vote) vote = 0 } else { // User wants to force vote to toggledVote. // Undo current vote, if any. applyChange(-1, toCountForVote: vote) // Apply new vote. vote = buttonVote applyChange(1, toCountForVote: vote) } 

}

 private func applyChange(change: Int, toCountForVote vote: Int ) { if vote == -1 { dislikeCount += change } else if vote == 1 { likeCount += change } 

}

 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "TableViewCell" // your cell identifier name in storyboard let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! PFTableViewCell cell.likeButton.selected = vote == 1 cell.dislikeButton.selected = vote == -1 cell.likeButton.titleLabel!.text = "\(likeCount)" cell.dislikeButton.titleLabel!.text = "\(dislikeCount)" return cell 

}

你可以用委托机制来做到这一点

为您的行动创buildprotocol

  protocol LikeProtocol { func likeOrDislikeActionAtRow(row: Int) } 

让你的TableViewController类确认这个协议:

 class YourTableViewController: UITableViewController, LikeProtocol { ... func likeOrDislikeActionAtRow(row: Int) { ... // Reload only you want cell self.tableView.beginUpdates() self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: 1)], withRowAnimation: UITableViewRowAnimation.Fade) self.tableView.endUpdates() ... } ... } 

添加到您的PFTableViewCell委托对象与protocolrowvariables的types:

 var delegate: LikeProtocol? var rowValue: Int? 

在你的func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)设置委托和行func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)

 cell.delegate = self cell.row = indexPath.row 

在你喜欢和不喜欢的动作中调用协议方法:

 @IBAction func likeButton(sender: UIButton) { .... delegate!.likeOrDislikeActionAtRow(row!) .... }