Сброс степпера в UITableViewCell (Swift) - PullRequest
0 голосов
/ 17 февраля 2020

У меня проблема с моим UIStepper. Я делаю счетную игру и каждый раз, нажимая «новое соревнование», я хочу, чтобы степпер сбросил значение. Я перепробовал много разных способов без результата.

Что мне делать?

class GameRoundTableViewCell: UITableViewCell {

    @IBOutlet weak var scoreLabel: UILabel!
    @IBOutlet weak var stepper: UIStepper!


    var index: IndexPath?

    var player : Player?

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    @IBAction func StepperCounter(_ sender: UIStepper) {
        player?.score = Int(sender.value)
        scoreLabel.text = String(Int(sender.value))

    }

}

class GameViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var previewButton: UIButton!
    var currentCompetitionsIndex = 0
    @IBOutlet weak var nextCompetition: UIButton!
    var gameRoundTableViewcell = "GameRoundTableViewcell"
    @IBOutlet weak var tabelViewGameRound: UITableView!
    let gameCellId = "GameCellId"
    var players : [Player]? = []
    var scoreLabel2 = GameRoundTableViewCell()
    var stepper2 = GameRoundTableViewCell()

    var questions : [Comepetitions]?
    @IBOutlet weak var textFieldCompInfo: UITextView!
    @IBOutlet weak var headingLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        nextCompetition.layer.cornerRadius = 26
        nextCompetition.clipsToBounds = true

        if let competition = questions?[currentCompetitionsIndex] {
            textFieldCompInfo?.text = competition.comepetitionsInfo
            headingLabel.text = competition.comepetitionsOption
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return players!.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell  {
        let cell = tableView.dequeueReusableCell(withIdentifier: gameCellId, for: indexPath as IndexPath) as! GameRoundTableViewCell

        cell.textLabel?.text = players?[indexPath.row].name
        if let score = players?[indexPath.row].score {
            cell.scoreLabel?.text = String(score)
            // cell.scoreLabel?.text =  "\(String(describing: person.score))"
        }
        cell.player = players?[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    func refresh(){
        tabelViewGameRound.reloadData()
    }


    @IBAction func previewCompeition(_ sender: UIButton)  {

        guard let quest = questions else {return}

        if currentCompetitionsIndex - 1 < quest.count  {
            currentCompetitionsIndex -= 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption

        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex == 0{
            previewButton.isHidden = true
        }
    }

**//When I Press this button I want to reset the stepper.**

    @IBAction func newCompetition(_ sender: UIButton)  {

        guard let players = players else {return}

        for player in players {
            player.scoreForEachRound.append(player.score)
            player.score = 0
        }
        tabelViewGameRound.reloadData()
        guard let quest = questions else {return}

        if currentCompetitionsIndex + 1 < quest.count  {
            currentCompetitionsIndex += 1
            textFieldCompInfo.text = quest[currentCompetitionsIndex].comepetitionsInfo
            headingLabel.text = quest[currentCompetitionsIndex].comepetitionsOption
        } else {
            currentCompetitionsIndex = 0
            performSegue(withIdentifier: "resultSegue", sender: nil)
        }
        if currentCompetitionsIndex > 0{
            previewButton.isHidden = false
        }

    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

        let vc = segue.destination as! FinalResultViewController
        vc.finalResualt = self.players
    }
}

1 Ответ

0 голосов
/ 17 февраля 2020

Я предполагаю, что вы наблюдаете следующее поведение, при котором дисплей в scoreLabel не синхронизируется c с элементом управления stepper. Этот пропущенный син c возникает в двух ситуациях:

  • При прокрутке в табличном представлении (повторное использование удаленных ячеек)
  • При сбросе всех очков игрока

Причина этого в том, что вы обновляете только scoreLabel, но не сбрасываете stepper. Оба элемента управления не зависят друг от друга, например, сброс одного не повлияет на другой. Поэтому степпер сохраняет старое (недействительное) значение, и при нажатии он продолжит обновлять метку этим значением.

Вам необходимо сделать следующее: в tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) также установите stepper на текущий счет:

if let score = players?[indexPath.row].score {
    cell.scoreLabel.text = String(score)
    cell.stepper.value = score
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...