create a custom dialog with a cancel button in swift

You can create a custom dialog with a cancel button by using UIAlertController and UIAlertAction. First, create an instance of UIAlertController and set its title, message, and preferred style. Then, create an instance of UIAlertAction with the style .cancel and set its title. Finally, add the action to the controller and present it.

Here's the code:

main.swift
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
    // handle cancel button tap
}

alertController.addAction(cancelAction)

present(alertController, animated: true, completion: nil)
308 chars
10 lines

In the closure of the UIAlertAction, you can handle what happens when the button is tapped. For example, you can dismiss the dialog or perform any other action.

gistlibby LogSnag