DEV Community

Avelyn Hyunjeong Choi
Avelyn Hyunjeong Choi

Posted on • Edited on

How to use UIAlertController in Xcode

IOS provides two constant values:

  • .alert
  • .actionSheet two constant values

.alert

    @IBAction func alertCalled(_ sender: Any) {
        let alert = UIAlertController(title: "Delete Message", message: "Are you sure you want to delete this message?", preferredStyle: .alert)

        // two buttons
        let cancelAction = UIAlertAction(title: "No", style: .cancel)
        let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
            print("message deleted!")
        }

        // add action to the alert
        alert.addAction(yesAction)
        alert.addAction(cancelAction)

        self.present(alert, animated: true)
    }
Enter fullscreen mode Exit fullscreen mode

alert image

.actionSheet

    @IBAction func alertCalled(_ sender: Any) {
        let alert = UIAlertController(title: "Delete Message!", message: "Are you sure you want to delete this message?", preferredStyle: .actionSheet)

        // two buttons
        let cancelAction = UIAlertAction(title: "No", style: .cancel)
        let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
            print("message deleted!")
        }

        // add action to the alert
        alert.addAction(yesAction)
        alert.addAction(cancelAction)

        self.present(alert, animated: true)
    }
Enter fullscreen mode Exit fullscreen mode

actionSheet

AlertControllers accepting user input
NOTE: you CANNOT use .actionSheet with addTextField() method

    @IBAction func alertWithTextFieldCalled(_ sender: Any) {
        let alert = UIAlertController(title: "Hello", message: "What is your name?", preferredStyle: .alert)

        alert.addTextField() { textField in
            textField.placeholder = "Enter your name"
        }

        // two buttons
        let cancelAction = UIAlertAction(title: "No", style: .cancel)
        let yesAction = UIAlertAction(title: "Yes", style: .destructive) { _ in
            let textField = alert.textFields![0] as UITextField
            guard let name = textField.text else {
                return
            }
            print("Hello \(name)")
        }

        // add action to the alert
        alert.addAction(yesAction)
        alert.addAction(cancelAction)

        self.present(alert, animated: true)
    }
Enter fullscreen mode Exit fullscreen mode

user input

result

Top comments (0)