我对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((无论我在这里输入的是什么内容)”。为什么可选的东西带括号?
答案 0 :(得分:1)
这是因为mealNameLabel.text
是Optional。使用?
声明选项,text
的{{1}}值的类型为UILabel
。要访问基础值,您必须使用String?
打开它,因此您的代码必须是
!
但是,如果标签的值为let alertController = UIAlertController(title: "Hello, \(mealNameLabel.text!))", message: "Enjoy our new app and make sure you rate us in AppStore!", preferredStyle: .alert)
,您的应用就会崩溃。如果您的应用在展开时崩溃,请参阅the post about it以获取更多信息。