在UITableViewCell

时间:2016-10-03 02:27:20

标签: ios swift uitableview swift3

MainVC.swift我正在捕捉自定义" PlayerCell"的标记。我想按increaseBtnUIButton),这会将playerLbl.textUILabel)增加1,但也会更新我的模型(PlayerStore.player.playerScore: Int)

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?

}

1 个答案:

答案 0 :(得分: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)    
    }

最后 - 要使一切正常,请将Main指定为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