我是 Swift 编程的新手,想知道是否可以显示用户在警报中输入的内容。这是我所做的:
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((无论我在此处键入什么))”。为什么 Optional 的东西会出现在括号中?
最佳答案
这是因为 mealNameLabel.text
是一个 Optional 。可选项用 ?
声明,UILabel
的 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
,您的应用程序将会崩溃。如果您的应用在解包时崩溃,请参阅 the post about it 了解更多信息。
关于swift - 如何在警报中显示用户输入? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904801/