2016-10-03 44 views
1

MainVC.swift我正在捕獲自定義「PlayerCell」的標記。我想按increaseBtnUIButton),這將增加了playerLbl.textUILabel)由一個也更新我的模型(PlayerStore.player.playerScore: Int)通過UITableViewCell中的UIButton更新模型

Main.swift:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell { 

     let player = players[indexPath.row] 

     cell.updateUI(player: player) 

     cell.increaseBtn.tag = indexPath.row 
     cell.decreaseBtn.tag = indexPath.row 

     return cell 

    } else { 
     return UITableViewCell() 
    } 

} 

PlayerCell.swift

class PlayerCell:UITableViewCell {

@IBOutlet weak var playerLbl: UILabel! 
@IBOutlet weak var increaseBtn: UIButton! 
@IBOutlet weak var decreaseBtn: UIButton! 
@IBOutlet weak var scoreLbl: UILabel! 
@IBOutlet weak var cellContentView: UIView! 

func updateUI(player: Player){ 
    playerLbl.text = player.playerName 
    scoreLbl.text = "\(player.playerScore)" 
    cellContentView.backgroundColor = player.playerColor.color 
} 

@IBAction func increaseBtnPressed(_ sender: AnyObject) { 
    let tag = sender.tag 
    // TODO: send this tag back to MainVC? 

} 
+0

你的'playerLbl'和'playerScore'在哪裏?我沒有在你的代碼片段中看到它。 – t4nhpt

+0

@ t4nhpt我用更多的相關信息更新了PlayerCell代碼。 'playerScore'是一個Player類的屬性,PlayerStore是一個管理播放器屬性的類 – Macness

回答

1

我會在這種情況下使用委託模式。創建一個Main.swift實現的協議,並且該PlayerCell.swift用作可選屬性。因此,例如:

protocol PlayerIncrementor { 
    func increment(by: Int) 
    func decrement(by: Int) 
} 

然後使用上Main.swift的擴展,實現此協議

extension Main: PlayerIncrementor { 
    func increment(by: int) { 
     //not 100% what you wanted to do with the value here, but this is where you would do something - in this case incrementing what was identified as your model 
     PlayerStore.player.playerScore += by 
    } 
} 

內PlayerCell.swift的,添加一個委託財產,並在您@IBAction

調用該委託增量法
class PlayerCell: UITableViewCell { 

    var delegate: PlayerIncrementor? 

    @IBOutlet weak var increaseBtn: UIButton! 

    @IBAction func increaseBtnPressed(_ sender: AnyObject) { 
     let tag = sender.tag 

     //call the delegate method with the amount you want to increment 
     delegate?.increment(by: tag)  
    } 

最後 - 使這一切工作,主要分配作爲代表到PlayerCell UITableViewCell.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

    if let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell", for: indexPath) as? PlayerCell { 

    //self, in this case is Main - which now implements PlayerIncrementor 
    cell.delegate = self 

    //etc 
+0

因此,如果有兩個按鈕(一個遞增,另一個遞減),我將如何添加一個委託給PlayerCell? – Macness

+0

@Macness - 您可以在協議中添加其他方法 - 我已更新示例 – syllabix

+0

@Macness - PlayerCell上是否有兩個按鈕? – syllabix

相關問題