how it possible to present alert by tapping button in nib?

103 Views Asked by At

i'm relatively new to programming and swift, I hope you understand that the beginning is sometimes difficult.

i have integrated a login form in a NIB and would like to call up an alert by func if the entry is incorrect. however, the call of present and dismiss an alert are only possible in the view controller. but what is the best way to solve this?

1

There are 1 best solutions below

6
Sandeep Bhandari On

Approach 1: You can either pass a weak reference of ViewController to which you add this nib as subview and use that to present alert

Approach 2: Use protocol/delegate or closure to communicate between nib's view class and view controller and present alert using the delegate method or closure

Approach 3: If you dont wanna do any of that, you can always access root view controller and try presenting the alert using root view controller

If you are using SceneDelegate then

if let scene = UIApplication.shared.connectedScenes.first, let sceneDelegate = scene.delegate as? SceneDelegate, let window = sceneDelegate.window, let rootViewController = window.rootViewController {
            let alert = UIAlertController(title: "your title", message: "your message", preferredStyle: .alert)
            rootViewController.present(alert, animated: true, completion: nil)
        }

And if you are not using SceneDelegate

        if let rootViewController = UIApplication.shared.keyWindow?.rootViewController {
            let alert = UIAlertController(title: "abcd", message: "efgh", preferredStyle: .alert)
            rootViewController.present(alert, animated: true, completion: nil)
        }