如何在警报中显示用户输入?(SWIFT)
我对Swift编程基本上是新手,想知道是否有可能显示用户在警报中输入的内容。这就是我所做的:如何在警报中显示用户输入?(SWIFT),swift,xcode,uialertcontroller,Swift,Xcode,Uialertcontroller,我对Swift编程基本上是新手,想知道是否有可能显示用户在警报中输入的内容。这就是我所做的: import UIKit class ViewController: UIViewController, UITextFieldDelegate { //MARK: Properties @IBOutlet weak var mealNameLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! override func vi
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)
}
}
当我运行程序时,它会显示“Hello,Optional((我在这里键入的任何内容都会打印出来))”。为什么可选的东西用括号显示 这是因为
mealNameLabel.text
是一个。选项用?
声明,UILabel
s的text
值为String?
类型。要访问基础值,必须使用将其展开代码>,因此您的代码必须是
let alertController = UIAlertController(title: "Hello, \(mealNameLabel.text!))", message: "Enjoy our new app and make sure you rate us in AppStore!", preferredStyle: .alert)
但是,如果标签的值为nil
,则您的应用程序将崩溃。如果你的应用程序在解包时崩溃,请参阅以获取更多信息