create a custom view dialog with one cancel button in swift

To create a custom view dialog with one cancel button in Swift, you can use a UIViewController subclass and present it modally using a UIAlertController.

First, create a new UIViewController subclass with your custom view. This view controller should include a cancelButton outlet and add the necessary actions to this button.

main.swift
class CustomViewController: UIViewController {

    @IBOutlet weak var cancelButton: UIButton!

    @IBAction func cancelDialog(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }
}
207 chars
9 lines

Next, present this view controller modally using a UIAlertController. In the handler parameter of the UIAlertAction, you can add any additional actions after the cancel button.

main.swift
let customVC = CustomViewController()

let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
alertController.setValue(customVC, forKey: "contentViewController")

let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alertController.addAction(cancelAction)

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

This will present your custom view dialog with the cancel button. When the cancel button is tapped, the dialog will dismiss.

gistlibby LogSnag