I am adding a UITextField
to a UIAlertController
, which appears as an AlertView
. Before dismissing the UIAlertController
, I want to validate the input of the UITextField
. Based on the validation I want to dismiss the UIAlertController
or not. But I have no clue how to prevent the dismissing action of the UIAlertController
when a button is pressed. Has anyone solved this problem or any ideas where to start ? I went to google but no luck :/ Thanks!
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
I've simplified matt's answer without the view hierarcy traversing. This is holding the action itself as a weak variable instead. This is a fully working example:
I realise that this is in Objectiv-C but it shows the principal. I will update this with a swift version later.
You could also do the same using a block as the target.
Add a property to your
ViewController
so that the block (closure for swift) has a strong reference@property (strong, nonatomic) id textValidationBlock;
Then create the
AlertViewController
like so:Cribbing off of @Matt's answer, here's how I did the same thing in Obj-C
You're correct: if the user can tap a button in your alert, the alert will be dismissed. So you want to prevent the user from tapping the button! It's all just a matter of disabling your UIAlertAction buttons. If an alert action is disabled, the user can't tap it to dismiss.
To combine this with text field validation, use a text field delegate method or action method (configured in the text field's configuration handler when you create it) to enable/disable the UIAlertActions appropriately depending on what text has (or hasn't) been entered.
Here's an example. We created the text field like this:
We have a Cancel action and an OK action, and we brought the OK action into the world disabled:
Subsequently, the user can't tap OK unless there is some actual text in the text field:
EDIT Here's the current (Swift 3.0.1 and later) version of the above code:
and
and