2017-08-27 65 views
0

我對Swift編程大致陌生,想知道是否可以顯示用戶在警報中輸入的內容。這是我做了什麼:如何在警報中顯示用戶輸入? (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,可選((無論我在這裏輸入獲取打印))」。爲什麼可選的東西出現在括號中?

回答

0

這是因爲mealNameLabel.textOptional。選項聲明?,textUILabel s是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獲取更多信息,瞭解您的應用在解包時崩潰的情況。

相關問題