I'm working on a controller that will allow a user to set the number of players they would like in a game. The view consists of some labels, a slider, and a button. The slider allows the user to select a value from 1-4 to select the number of players. One of those labels is set to x Player(s) Selected where x is the slider's value rounded to the nearest Int. The button then sends the user to the game (another view) which is handled by a different View Controller (VC). I'm trying to send the number of players to the other VC but the value does not appear to be saved outside of the IBAction function.
As a possible fix, I've tried using an instance of GameViewController in NumberOfPlayersViewController.swift and updating the variable in setNumOfPlayers, which also did not work. Am I just missing something or is updating a variable in an IBAction not possible?
// NumberOfPlayersViewController.swift import UIKit class NumberOfPlayersViewCOntroller: UIViewController { // Default number of players var numOfPlayers = 1 // UIObjects <Label here> <Slider here> @IBAction private func setNumOfPlayers(_ sender: UISlider) -> Void { // Get the number of players and update the label numOfPlayers = Int(sender.value) // Originally float, rounds the value to the nearest Int label.text = "\(numOfPlayers) Player(s) Selected" // Updates label print(numOfPlayers) // Prints the rounded value } func getNumberOfPlayers() -> Int { return numOfPlayers // Only returns the default value of 1 // GameViewController.swift class GameViewController:UIViewController { let NumberOfPlayersVC = NumberOfPlayersViewController() lazy var numOfPlayers = NumberOfPlayersVC.getNumberOfPlayers() // Lazy as `self` is not available override func viewDidLoad() { super.viewDidLoad() print(numOfPlayers) // Prints 1 } } These views that these ViewControllers handle are connected via a Seque.
https://stackoverflow.com/questions/67409855/variable-of-self-is-not-saved-when-setting-a-value-in-an-ibaction May 06, 2021 at 07:09AM
没有评论:
发表评论