[英]UITextfield unresponsive. UITextfield embedded in alert isn't working
我在表格視圖中工作,我希望用戶能夠單擊一個按鈕,該按鈕會顯示帶有文本字段的警報。 他們在文本字段中輸入一個字符串,按回車鍵,該字符串在表格中顯示為一行。 這是我的代碼,用於在按下右上角的加號圖標時顯示警報和文本字段。 一旦我在模擬器中按下它,應用程序變得無響應,文本字段中沒有 cursor,我無法使用模擬鍵盤或我的實際鍵盤輸入。 這是代碼和圖像:
@IBAction func addButtonPress(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Category", style: .default) { (action) in
let newCategory = Category(context: self.context)
newCategory.name = textField.text!
self.categoryArray.append(newCategory)
self.saveCategories()
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Create new category"
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
您可以改為這樣做。 基本上它會獲取警報中第一個文本字段的值。
@IBAction func addButtonPress(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Add New Category", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Category", style: .default) { (action) in
guard let categoryName = alert.textFields?.first?.text else { return }
let newCategory = Category(context: self.context)
newCategory.name = categoryName
self.categoryArray.append(newCategory)
self.saveCategories()
}
alert.addTextField { alertTextField in
alertTextField.placeholder = "Create new category"
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.