-1

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.

Frederick C. Lee
  • 9,019
  • 17
  • 64
  • 105

2 Answers2

1

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.

Andrew
  • 26,706
  • 9
  • 85
  • 101
Asif Mujtaba
  • 447
  • 6
  • 17
-1
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

Mostafa Sh
  • 104
  • 2
  • 6
  • this is not a complete answer. What storyboard are you using? What is the view controller? – bze12 Oct 16 '22 at 22:52