FA95
FA95

Reputation: 43

How to display user input in an Alert? (SWIFT)

I'm roughly new to Swift programming, and was wondering if it is possible to display what the user inputted in the alert. This is what I have done:

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

//MARK: Properties
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    // Handle the text field’s user input through delegate callbacks.
    nameTextField.delegate = self
}

//MARK: UITextFieldDelegate

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    // Hide the keyboard.
    textField.resignFirstResponder()
    return true
}

func textFieldDidEndEditing(_ textField: UITextField) {
    mealNameLabel.text = textField.text
    mealNameLabel.sizeToFit()
}

//MARK: Actions
@IBAction func setDefaultLabelText(_ sender: UIButton) {
    mealNameLabel.text = "Default Text"
    mealNameLabel.sizeToFit()
    let alertController = UIAlertController(title: "Hello, \(mealNameLabel.text))", message: "Enjoy our new app and make sure you rate us in AppStore!", preferredStyle: .alert)
    let defaultAction = UIAlertAction(title: "Close Alert", style: .default, handler: nil)
    alertController.addAction(defaultAction)
    present(alertController, animated: true, completion: nil)
}

}

When I run the program, it display "Hello, Optional((whatever I type here gets printed))". Why does the Optional thing appear with brackets?

Upvotes: 0

Views: 720

Answers (1)

Papershine
Papershine

Reputation: 5223

This is because mealNameLabel.text is an Optional. Optionals are declared with a ? and the text value of UILabels is of type String?. To access the underlying value, you have to unwrap it by using !, so your code would have to be

let alertController = UIAlertController(title: "Hello, \(mealNameLabel.text!))", message: "Enjoy our new app and make sure you rate us in AppStore!", preferredStyle: .alert)

However, if the value of the label is nil, your app would crash. See the post about it for more info if your app crashes while unwrapping it.

Upvotes: 1

Related Questions