[SWIFT] Alert with TextField

Introduction

It's convenient and useful because you don't have to arrange the UI each time you want to enter something.

Completed form スクリーンショット 2021-01-05 15.23.20.png

environment

Xcode 12.3

code


    let title = "Title"
    let msg = "Message"
    
    let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
    
    //OK button settings
    let okAction = UIAlertAction(title: "OK", style: .default, handler: {(action:UIAlertAction!) -> Void in
      
      //What to do when the OK button is pressed in an alert with a text field
      //Optional binding and retrieval of the value entered in the text field
      if let str = alert.textFields?[0].text{
        print(str)
      }
    })
    
    alert.addAction(okAction)
    
    //Cancel button settings
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    alert.addAction(cancelAction)
    
    //Add text field
    alert.addTextField(configurationHandler: {(textField:UITextField!) -> Void in
      //You can customize the text field here
      textField.placeholder = ""
      textField.keyboardType = .default
      
    })
    
    //If you want to add more than one, write that number
    // alert.addTextField(configurationHandler: {(textField: UITextField!) -> Void in
    //     textField.placeholder = "text"
    // })
    
    //Display alerts on screen
    self.present(alert, animated: true, completion: nil)
  }

If you want to use multiple textFields, write multiple addTextFields

Recommended Posts

Alert with TextField
Create two DatePickers linked with TextField
Alert slack with alert manager in Docker environment