2016-10-03 3 views
1

В MainVC.swift Я занимаюсь тегом моего обычая «PlayerCell». Я хочу, чтобы нажать increaseBtn (UIButton), который будет увеличивать playerLbl.text (UILabel) один, но и обновить моя модель (PlayerStore.player.playerScore: Int)Обновить модель через UIButton в UITableViewCell

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

класс 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) 
} 

Затем использовать расширение на 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

Смежные вопросы