2016-10-03 9 views
1

MainVC.swift私はカスタム "PlayerCell"のタグをキャプチャしています。UITableViewCell内のUIButtonでモデルを更新

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

:私は1つで playerLbl.textUILabel)をインクリメントするだけでなく、私のモデル (PlayerStore.player.playerScore: Int)

Main.swiftを更新しますincreaseBtnUIButton)を押します

クラス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はPlayer属性を管理するクラスです – Macness

答えて

1

この場合、デリゲートパターンを使用します。 Main.swiftが実装するプロトコルを作成し、PlayerCell.swiftはオプションのプロパティとして使用します。だから、例えば:

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

はその後、このプロトコルにPlayerCell.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 
    } 
} 

を実装するデリゲートプロパティを追加し、@IBAction

にデリゲートインクリメントメソッドを呼び出すためにMain.swiftに拡張子を使用します最後に
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

2つのボタン(1つずつ増分、もう1つが減る)がPlayerCellにどのように追加されますか? – Macness

+0

@Macness - プロトコルに別のメソッドを追加することができます - 私は例を更新しました – syllabix

+0

@Macness - PlayerCellには2つのボタンがありますか? – syllabix

関連する問題