2016-10-03 79 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