微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

UITextfield 无响应嵌入在警报中的 UITextfield 不起作用

如何解决UITextfield 无响应嵌入在警报中的 UITextfield 不起作用

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

@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)
    
}

enter image description here

enter image description here

解决方法

您可以改为这样做。基本上它获取警报中第一个文本字段的值。

@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)
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。