Tableview单元格按钮选择错误

时间:2016-07-28 10:50:18

标签: swift uitableview cell

我有一个tableview,其中包含单元格左侧的按钮。运行效果很好,当我选择一个按钮时,它会改变它的图像背景。问题是,当我选择一个按钮ButtonOne selection时,当我向下滚动桌面视图时,它会选择其他按钮,Other buttons selected我的代码是这样的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableview.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PlayerCell
    cell.BtnAdd.tag = indexPath.row
    cell.BtnAdd.addTarget(self, action: #selector(CreateTeamTwo.PlayerAdded(_:)), forControlEvents: .TouchUpInside)
    return cell  
}

func PlayerAdded(sender: UIButton){
    // let buttonTag = sender.tag
    sender.setImage(UIImage(named: "btn_buy_minus.png"), forState: UIControlState.Normal)        
} 
你可以帮我吗?

1 个答案:

答案 0 :(得分:0)

使用一个Array存储选定的indexPaths按钮标记。并在选择器方法中存储所有发件人标签并重新加载tableView。并且在cellForRow方法中检查当前索引路径是否包含在所选数组中,然后显示减去图像,否则显示加上图像。

var selected = [Int]()


func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableview.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PlayerCell
    cell.BtnAdd.tag = indexPath.row
    cell.BtnAdd.addTarget(self, action: #selector(CreateTeamTwo.PlayerAdded(_:)), forControlEvents: .TouchUpInside)

    if selected.contains(indexPath.row) {
        cell.btn.setImage(UIImage(named: "btn_buy_minus.png"), forState: .Normal)
    } else {
        // here set the plus image
        cell.btn.setImage(UIImage(named: "btn_buy_plus.png"), forState: .Normal)
    }
    return cell
}

func PlayerAdded(sender: UIButton){
    selected.append(sender.tag)
    self.tableView.reloadData()
}
相关问题