1

I am making a game in Swift that records the high score and initials (similar to pinball records) and displays it on the game screen as labels. I am using the code below to record the high score and initials on my phone and update them. For the time being, this program will only be on my phone so I am not concerned about storing or updating data on a remote database.

What I don't know how to do (yet) is make a little popup asking the user to enter their initials on a keyboard when the quit button is pressed, if they have the current high score. Ideally, I want it to be able to only accept 3 characters and to update the initials label immediately, before the user is taken to a different view controller.

@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var highScoreLabel: UILabel!
@IBOutlet weak var highScoreInitialsLabel: UILabel!
var score : Int = 0

//Stores and sets high score initials
var oldHighScoreInitials : String = "AAA"
var highScoreInitials : String {
    get {
        return UserDefaults.standard.string(forKey: "highScoreInitials") ?? "AAA"
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "highScoreInitials")
    }
}


//Stores and sets high score
var oldHighScore : Int = 0
var highScore : Int {
    get {
        return UserDefaults.standard.integer(forKey: "highScore")
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "highScore")
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    //Updates high score and initials labels with stored highest score and associated initials
    highScoreLabel.text = String(highScore)
    highScoreInitialsLabel.text = String(highScoreInitials)
    oldHighScore = highScore
    oldHighScoreInitials = highScoreInitials
}


//Asks for initials if new high score, and segues to Main VC
@IBAction func quitButtonPressed(_ sender: AnyObject) {
    if (score > highScore){
        highScore = score
        print("Ask for initials")
        print("Game over, thanks for playing!"
        print("Segue to Main VC")
    }

    else {
        print("Game over, thanks for playing!")
        print("Segue to Main VC")
    }
}

Thank you very much to anybody that offers assistance or advice.

2 Answers 2

1

Here you go, pretty simple using UIAlertViewController:

//Asks for initials if new high score, and segues to Main VC
@IBAction func quitButtonPressed(_ sender: AnyObject) {
    if (score > highScore){
        highScore = score

        let alert = UIAlertController(title: "NEW HIGH SCORE", message: "Please enter your initials", preferredStyle: .alert)

        alert.addTextField(configurationHandler: configurationTextField)

        alert.addAction(UIAlertAction(title: "DONE", style: .default, handler:{ (action) in

        //First example of updating initials
        guard alert.textFields![0].text?.characters.count != 0 else{
            return
        }

        self.oldHighScore = self.highScore
        self.oldHighScoreInitials = alert.textFields![0].text

        //Segue to Main VC
        }))

        present(alert, animated: true, completion: nil)
    }

    else {
        print("Game over, thanks for playing!")
        print("Segue to Main VC")
    }
}

func configurationTextField(textField: UITextField!){
    textField.delegate = self
    textField.textAlignment = .center
    textField.placeholder = "_ _ _"
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let text = textField.text else { return true }
    let count = text.count + string.count - range.length
    return count <= 3
}

//Second example of updating initials
func textFieldDidEndEditing(_ textField: UITextField) {
    oldHighScore = highScore
    oldHighScoreInitials = textField.text
}

And finally your controller should conform to the UITextFieldDelegate protocol:

class yourController: UIViewController, UITextFieldDelegate
8
  • That looks like a good method, but how would I tie the user input to string variable highScoreInitials?
    – Robert
    Dec 28, 2018 at 6:41
  • By using the others methods from the textfield delegate
    – Arie Pinto
    Dec 28, 2018 at 9:34
  • The method looked good, but I am getting the following error: Warning: Attempt to present <UIAlertController: 0x10606ae00> on <GameViewController: 0x106834c00> whose view is not in the window hierarchy! I have looked up this error and tried to fix it using a dozen fixes shown on StackOverflow, but I cannot get past it and get the alert to pop up.
    – Robert
    Dec 28, 2018 at 19:59
  • Well I need more information in order to help you, are you using SpriteKit for this game? does your view controller initialize an SKScene? if not, share more of your view controller class code.
    – Arie Pinto
    Dec 28, 2018 at 22:13
  • 1
    Well it appears you are in the Addition2x2ViewController but the error clearly says you are trying to present the pop up from GameViewController. Why is that? i still don't have enough information to go on, in the IB (storyboard) are you using unwind segue when quitButtonIsPressed? are you using a navigation controller? for you to be able to see the pop up, the Addition2x2ViewController must be the one to present it, then you can pop it back to GameViewController.
    – Arie Pinto
    Dec 28, 2018 at 23:55
1

After working with Arie Pinto, we determined that my segue was preventing the alert from working and was presenting an error stating that my program was attempting to present an alert whose view was not in the window hierarchy.

I programmed my segue by ctrl+dragging my quit button to a different view controller, without writing any code.

My solution to this will be to write in performSegue code in the quitButtonPressed function to allow the alert and initial update code to perform their actions before changing windows.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.