Tableview单元格按钮选择错误
问题描述:
我有一个tableview包含单元格左边的按钮。运行效果很好,当我选择一个按钮时,它会改变它的图像背景。问题是,当我选择一个按钮ButtonOne selection,它选择其他的按钮,当我滚动tableview中下来,Other buttons selected我的代码是这样:Tableview单元格按钮选择错误
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)
}
你能帮助我吗?
答
取一个数组来存储选定的indexPaths按钮标记。并在选择器方法中存储所有发件人标签并重新加载tableView。并在cellForRow方法检查当前的indexpath是否包含在选定的数组中,然后显示减号图像,否则显示加图像。
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()
}
谢谢!这工作!全国联保:) –
您的欢迎:) –