swift - 如何在警报中显示用户输入? ( swift )

标签 swift xcode uialertcontroller

我是 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 。可选项用 ? 声明,UILabeltext 值是 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/

相关文章:

ios - 如何使用 Swift 在 UICollectionViewCell 中设置 UIButton 的标题

ios - 如何知道哪个 SKSpriteNode 受到 Swift 中碰撞检测的影响?

ios - 临时构建(Xcode 4.2、Lion)不会安装在 4.2.1 设备上

Swift 3 使用 uialertcontroller 添加新行到 uitableviewcontroller

swift - 添加 "Load More"到 tableview NSObject json 解析

c++ - 如何让 Xcode 4.1 代码完成自动工作?

ios - UIImagePickerController 崩溃应用程序 | swift 3,Xcode8

ios - Touch ID "Try Again"警报 View 的标题是否可自定义?

ios - UIActionSheet/UIAlertController 多行文本

ios - 使应用程序出现在共享面板中以接受来自其他应用程序的选定文本