HomeiOS Developmentios - UIAlertController: Examine if there's textual content in a number of...

ios – UIAlertController: Examine if there’s textual content in a number of UITextFields earlier than button is pressed


Swift 5, Xcode 14.2

I’ve received two UIViewControllers that each should show the identical UIAlertController (just one is loaded at a time). As a substitute of utilizing the identical code twice, I added it to my current static class that is already used to cross knowledge round (solely accessed by one thread at a time).

In my static class:

static func createLoginDialog(buttonPressed: @escaping (_ username:String, _ pw:String) -> Void) -> UIAlertController {
    let alert = UIAlertController(title: "Login", message: "", preferredStyle: .alert)

    alert.addAction(UIAlertAction(title: "Log in", fashion: .default, handler: { (motion: UIAlertAction!) in
        let u = alert.textFields![0].textual content!
        let p = alert.textFields![1].textual content!
        buttonPressed(u,p)
    }))
        
    alert.addTextField { textField in
        textField.placeholder = "Enter Username"
    }
    
    alert.addTextField { textField in
        textField.placeholder = "Enter Password"
    }
    
    return alert
}

Calling code within the UIViewController lessons:

func doSomethingAndShowAlert() {
    //Do one thing

    let alert = MyStaticClass.createLoginDialog() {
        (username,pw) in
        //Do stuff with non-empty enter
    }
    self.current(alert,animated: true, completion: nil)
}

With this code the dialog is dismissed when you press the button, it doesn’t matter what the enter is. The enter is checked for validity within the calling perform however I do not wish to shut the dialog, except there’s textual content in each UITextFields. In accordance with solutions to different questions, you may’t preserve the dialog from being dismissed mechanically however you may disable the motion/button till there’s textual content, which is okay with me.

There are a few strategies right here (just for a single UITextField) however Xcode complains concerning the @objc/motion: #selector if I add it to my code (as a result of my class is static?). I additionally tried to mix this single TF model with this multi TF model however the motion perform isn’t known as (possibly as a result of I do not set it in viewDidLoad()?).

I am conscious that this may be rather a lot simpler with a customized view that is displayed as an alternative of a UIAlertController however I wish to strive it this fashion.

How do I test if there’s textual content in each UITextFields, earlier than enabling the button, in my static class/perform?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments