2016-07-28 87 views
1

我有一個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)   
} 

你能幫助我嗎?

回答

0

取一個數組來存儲選定的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() 
} 
+0

謝謝!這工作!全國聯保:) –

+0

您的歡迎:) –