Create a custom UIAlertController

1.3k Views Asked by At

Goal: To create an alert with a UITextField data entry plus two buttons: 'Accept' & 'Cancel'.

I understand that the UIAlertViewController is not to be altered.

I tried to make a UIViewController but am having trouble with the VC's view filling the entire screen containing a member alert/modal view.

The simplest way is merely make a UIView and control it from the host.

What I want is to merely display a *customizable* dialog/alert as a *presented* UIViewController. By customized alert, I mean with the ability to accept data from user.

I'm also curious how that would be done via SwiftUI.

2

There are 2 best solutions below

1
Mostafa Sh On
extension UIViewController {

func showAlertWithCancel(title: String, message: String, okAction: String, cancel: String, completion: ((Bool, String) -> Void)? = nil ) {
    let sb_main = UIStoryboard.init(name: "Main", bundle: nil)
    let vc: CustomNewAlertVC = sb_main.instanceVC()
    vc.modalPresentationStyle = .custom
    vc.modalTransitionStyle = .crossDissolve
    vc._ok = okAction
    vc._msg = message
    vc._title = title
    vc._cancel = cancel
    vc.delegate = { aa in
        completion?(aa)
    }
    DispatchQueue.main.async {
        self.present(vc, animated: true, completion: nil)
    }
 }
}

To show alert use: self.showAlertWithCancel(title: "Test" ....

enter image description here

3
Asif Mujtaba On

If you consider UIKit, then you can put a text field inside UIAlertController like this.

let alertController = UIAlertController(title: "Text Entry", message: "", preferredStyle: .alert)

// Add a textField to your controller, with a placeholder value & secure entry enabled
alertController.addTextField { textField in
    textField.placeholder = "Enter Text"
    textField.isSecureTextEntry = true
    textField.textAlignment = .center
}

// A cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
    print("Canelled")
}

// This action handles your confirmation action
let confirmAction = UIAlertAction(title: "Accept", style: .default) { _ in
    print("Current password value: \(alertController.textFields?.first?.text ?? "None")")
}

// Add the actions, the order here does not matter
alertController.addAction(cancelAction)
alertController.addAction(confirmAction)

present(alertController, animated: true, completion: nil)

enter image description here

Let me know if it answers your question.