问题描述
我在一个表格视图中工作,我希望用户能够点击一个按钮来显示一个带有文本字段的警报。他们在文本字段中输入一个字符串,按回车键,该字符串在表格中显示为一行。这是我的代码,用于在按下右上角的加号图标时显示警报和文本字段。在模拟器中按下它后,应用程序变得无响应,文本字段中没有光标,并且我无法使用模拟键盘或我的实际键盘输入。这是代码和图片:
@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)
}