我正在尝试创建一个简单的应用程序,其中表视图中的每个单元格都有一个心形按钮。如果我点击心形按钮,它应该会被填满。不幸的是,每次我点击它,其他细胞中的其他心脏也会被填满。我发现这是由于细胞回收。我尝试了很多不同的方法来解决这个问题,但不确定确切的过程是什么。这是应用程序的代码:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:heartcell = tableView.dequeueReusableCellWithIdentifier("heart") as! heartcell
cell.heartButton.tag = indexPath.row
cell.heartButton.setImage(UIImage(named: "heartsUnfillled"), forState: UIControlState.Normal)
cell.heartButton.setImage(UIImage(named: "heartsFilled"), forState: UIControlState.Selected)
cell.heartButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
return cell
}
func buttonClicked(sender:UIButton)
{
let ip = NSIndexPath(forRow: sender.tag, inSection: 0)
let cell = someTB.cellForRowAtIndexPath(ip) as! heartcell
cell.heartButton.selected = !cell.heartButton.selected
}
很明显,细胞正在被回收,但这不起作用。我尝试过将单元格存储在一个数组中,将它们各自的索引存储在一个中,但无论如何,我仍然会遇到同样的问题,即我无法控制填充的心。有人知道怎么解决这个问题吗?谢谢
您应该声明一个集合:
var filledHeartSet = Set<NSIndexPath>()
并在你的代码中使用它,如下所示:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:heartcell = tableView.dequeueReusableCellWithIdentifier("heart") as! heartcell
cell.heartButton.tag = indexPath.row
cell.heartButton.setImage(UIImage(named: "heartsUnfillled"), forState: UIControlState.Normal)
cell.heartButton.setImage(UIImage(named: "heartsFilled"), forState: UIControlState.Selected)
cell.heartButton.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)
// set current state for heart button
cell.heartButton.selected = filledHeartSet.contains(indexPath)
return cell
}
func buttonClicked(sender:UIButton)
{
let ip = NSIndexPath(forRow: sender.tag, inSection: 0)
// only store filled heart indexPath
if filledHeartSet.contains(ip) {
filledHeartSet.remove(ip)
} else {
filledHeartSet.insert(ip)
}
let cell = someTB.cellForRowAtIndexPath(ip) as! heartcell
cell.heartButton.selected = !cell.heartButton.selected
}