Swift 5, Xcode 14.2
I’ve received two UIViewController
s 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 UITextField
s. 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 UITextField
s, earlier than enabling the button, in my static class/perform?