Как добавить текстовое поле в UIAlertController в Swift
Я пытаюсь показать UIAlertController с UITextView. Когда я добавляю строку:
//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
}
Я получаю ошибку времени выполнения:
фатальная ошибка: неожиданно обнаружил нулю при разворачивании необязательное значение
let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)
//cancel button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
//Create an optional action
let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
let text = (alertController.textFields?.first as! UITextField).text
println("You entered (text)")
}
alertController.addAction(nextAction)
//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.textColor = UIColor.greenColor()
}
//Present the AlertController
presentViewController(alertController, animated: true, completion: nil)
это представлено внутри моего ViewController через IBAction.
Я скачал код отсюда:http://sourcefreeze.com/uialertcontroller-ios-8-using-swift/ и он отлично работает. Я скопировать и вставить этот метод в мой код и он ломается. Наличие self на последнюю строку не влияет.
8 ответов:
Swift 4
alert.addTextField(configurationHandler: { (textField) in textField.placeholder = "Enter First Name" })
используйте этот код, я использую этот код в моем приложении.
@IBAction func addButtonClicked(sender : AnyObject){ let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.Alert) alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in textField.placeholder = "Enter Second Name" } let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { alert -> Void in let firstTextField = alertController.textFields![0] as UITextField let secondTextField = alertController.textFields![1] as UITextField }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action : UIAlertAction!) -> Void in }) alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in textField.placeholder = "Enter First Name" } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.presentViewController(alertController, animated: true, completion: nil) }отредактировано: версия Swift 3.0
@IBAction func addButtonClicked(_ sender: UIButton){ let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter Second Name" } let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in let firstTextField = alertController.textFields![0] as UITextField let secondTextField = alertController.textFields![1] as UITextField print("firstName \(firstTextField.text), secondName \(secondTextField.text)") }) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in }) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter First Name" } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) }
чтобы добавить текстовое поле в Swift 3.0:
let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in let textField = alertController.textFields![0] as UITextField // do something with textField })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in textField.placeholder = "Search" }) self.present(alertController, animated: true, completion: nil)
поэтому я начал проверять, что могло бы отличаться в моем коде от рабочего кода. Я заметил, что мой ViewController расширяет
UITextFieldDelegateчто, по-видимому, означает, что мне нужно установить делегат любого дочернего UITextView:
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in searchTextField = textField searchTextField?.delegate = self //REQUIRED searchTextField?.placeholder = "Enter your search terms" }
как добавить текстовое поле в AlertView? Давайте будем короткими и простыми.
это работает для Swift 3.0 и выше.
var nameField: UITextField? let alertController = UIAlertController(title: "Add Number", message: nil, preferredStyle: .alert) // Add textfield to alert view alertController.addTextField { (textField) in nameField = textField }во-первых, вы создаете экземпляр объекта
UIAlertControllerи затем вы добавляете к нему текстовое поле, обращаясь кaddTextFieldчленUIAlertControllerкласса.
добавить текстовое поле в UIAlertController и текстовое поле отображения текста на UILabel в Swift
let alert = UIAlertController(title: "Alert", message: "", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "First Name" } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert?.textFields![0] self.label.text = textField?.text })) self.present(alert, animated: true, completion: nil)
отличный ответ небольшая модификация, чтобы показать, как можно использовать текстовое поле:
func addRow (row: Int, bodin: String, flag: Int) { let alertController = UIAlertController(title: bodin, message: "", preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in _ = alertController.textFields![0] as UITextField })) alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) alertController.addTextField(configurationHandler: {(textField : UITextField!) -> Void in switch flag { case 0: textField.keyboardType = UIKeyboardType.phonePad textField.placeholder = "Enter Number" case 1: textField.keyboardType = UIKeyboardType.emailAddress textField.placeholder = "Enter Email" default: break } })
для Swift 4.0 вы можете использовать этот образец кода, успешно протестированный в моем проекте:
@IBAction func withdrawTapped(_ sender: UIButton) { let alertController = UIAlertController(title: "Token withdraw", message: "", preferredStyle: .alert) let withdrawAction = UIAlertAction(title: "Withdraw", style: .default) { (aciton) in let text = alertController.textFields!.first!.text! if !text.isEmpty { self.presentAlert( title: "Succesful", message: "You made request for withdraw \(textField.text) tokens") } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in } alertController.addTextField { (textField) in textField.placeholder = "999" textField.keyboardType = .decimalPad } alertController.addAction(withdrawAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) }
устранение:
Swift 4.2
попробовать следующие строки и посмотреть, если это работает:
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.alert) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter Second Name" } let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.default, handler: { alert -> Void in let firstTextField = alertController.textFields![0] as UITextField let secondTextField = alertController.textFields![1] as UITextField }) let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: { (action : UIAlertAction!) -> Void in }) alertController.addTextField { (textField : UITextField!) -> Void in textField.placeholder = "Enter First Name" } alertController.addAction(saveAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil)надеюсь, что это помогает.
Comments