Building an alert dialog box with text input in Swift is a common problem for iOS developers.
In this tutorial, we’ll build one together. The final result will look something like this:
First we need to build an alert in Swift. To show an alert to your view when it opens, add to your viewDidAppear
function:
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: .alert)
self.present(alert, animated: true, completion: nil)
}
When you run your application you should get something like this:
To add the text input field into our app, we’ll call the function addTextfield
alert.addTextField { (textField) in
textField.placeholder = "Default placeholder text"
}
It should now look like this:
Let’s add a way for our user to submit text and capture that text.
alert.addAction(UIAlertAction(title: "Submit", style: .default, handler: { [weak alert] (_) in
guard let textField = alert?.textFields?[0], let userText = textField.text else { return }
print("User text: \(userText)")
}))
All together your code should now look like this:
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Default placeholder text"
}
alert.addAction(UIAlertAction(title: "Submit", style: .default, handler: { [weak alert] (_) in
guard let textField = alert?.textFields?[0], let userText = textField.text else { return }
print("User text: \(userText)")
}))
self.present(alert, animated: true, completion: nil)
}
}
To add more text fields, we can simply call addTextField
multiple times. Here’s a code example:
class ViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
let alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: .alert)
alert.addTextField { (textField) in
textField.placeholder = "Default placeholder text"
}
alert.addTextField { (textField) in
textField.placeholder = "Second textfield placeholder text"
}
alert.addAction(UIAlertAction(title: "Submit", style: .default, handler: { [weak alert] (_) in
if let textField = alert?.textFields?[0], let userText = textField.text {
print("User text: \(userText)")
}
if let textField = alert?.textFields?[1], let userText = textField.text {
print("User text 2: \(userText)")
}
}))
self.present(alert, animated: true, completion: nil)
}
}
And this is what it looks like:
The Complete iOS App Development Bootcamp
Disclosure: This website may contain affiliate links, meaning when you click the links and make a purchase, we receive a commission.