Как обновить метку в другом контроллере представления? - PullRequest
0 голосов
/ 28 апреля 2020

Я очень плохо знаком с кодированием. Я создал игру, и в верхнем углу GameViewController есть scoreLabel. Я создал другую метку в другом контроллере представления (ShopViewController) с именем moneyLabel. Я хочу, чтобы денежная метка была равна счету. Я сделал так, чтобы моя метка очков сбрасывалась каждый раз, когда вы запускаете новую игру, но я хочу, чтобы мои деньги оставались такими же, чтобы я мог использовать эти деньги для покупок в игре.

Я не знаю, как чтобы он обновился. Я попытался: gameViewController = GameViewController(), а затем с помощью кода обновить мой ярлык, но он не работает. Мой ярлык не обновляется вообще. Остается на 0.

1 Ответ

0 голосов
/ 29 апреля 2020

Я думаю, что вам нужно использовать некоторую структуру модели, где вы можете добавить свой счет или любые другие данные и легко манипулировать им:

struct GameData{
    var totalScore: Int = 0
    var currentGameScore: Int = 0

    func invalidateCurrentScore(){
        totalScore += currentGameScore
        currentGameScore = 0
        //call this method when you need to set your current score to 0, and pass all the accumulated points to your total score (f.ex. in the end of the game)
    }

    //some other data like player's name and etc...
}

Вам также необходимо создать протокол делегирования для использования его метода в ShopViewController и возвращение игровых данных в GameViewController:

protocol ShopViewControllerDelegate{
     func updateGameData(by gameData: GameData)
}

GameViewController с новыми деталями:

class GameViewConroller: UIViewController, ShopViewControllerDelegate{

    @IBOutlet weak var scoreLabel: UILabel!
    var gameData: GameData!

    override func viewDidLoad(){
        super.viewDidLoad()
        gameData = GameData()
        updateScoreLabel()
    }

    private func updateScoreLabel(){ //call it anyTime when you manipulate the score of current game
        scoreLabel.text = "Score: \(gameData.currentGameScore)"
    }

    func updateGameData(by gameData: GameData){ //This is the delegate's method that ShopViewController needs to trigger when you buy something in the shop
         self.gameData = gameData
         updateScoreLabel()
    }


    override func prepare(for segue: UIStoryboardSegue, 
      sender: Any?){
        if let shopViewController = segue.destination as? ShopViewController{
            //passing game data to ShopViewController
            shopViewController.gameData = self.gameData
            shopViewController.delegate = self //!IMPORTANT
        }
    }
}

И вот некоторые свойства и методы, которые должен иметь ваш ShopViewController:

class ShopViewController{
    @IBOutlet weak var totalScoreLabel: UILabel!
    var gameData: GameData!
    var delegate: ShopViewControllerDelegate?

    override func viewDidLoad(){
        super.viewDidLoad()
        updateTotalScoreLabel()
    }
    private func updateTotalScoreLabel(){
        totalScoreLabel.text = "Total Score: \(gameData.totalScore + gameData.currentGameScore)"
    }

    private func purchasingSomething(){
        //logic of getting price of an item
        gameData.currentGameScore -= price
        if gameData.currentGameScore < 0{
            gameData.totalScore += gameData.currentGameScore
            gameData.currentGameScore = 0
            //if your current score is less than 0 after some purchase, your total score decreases and the current score becomes 0
        }
        updateTotalScoreLabel()
        delegate?.updateGameData(by gameData: gameData) //Pass refreshed gameData back to the GameViewController
    }
}

Также в Swift есть переменные c, но они очень просты в использовании. Делегаты приносят больше удовольствия и делают код более красивым.

struct GameData{
    static var totalScore: Int = 0
    static var currentGameScore: Int = 0
}

Удачи и приятного времяпровождения с игрой dev:)

...