我正在向UITextField
添加UIAlertController
,其显示为AlertView
。在驳回UIAlertController
之前,我想验证UITextField
的输入。基于验证,我想要忽略UIAlertController
。但我不知道如何在按下按钮时阻止UIAlertController
的解雇操作。有没有人解决这个问题或任何想法从哪里开始?我去谷歌但没有运气:/谢谢!
答案 0 :(得分:66)
您已更正:如果用户可以点按提醒中的按钮,则系统会将其解除警报。所以你想阻止用户点击按钮!这只是禁用UIAlertAction按钮的问题。如果禁用了提醒操作,则用户无法点击提醒操作。
要将其与文本字段验证相结合,请使用文本字段委托方法或操作方法(在创建时在文本字段的配置处理程序中配置),以根据文本的具体情况适当启用/禁用UIAlertActions(或者还没有输入。
这是一个例子。我们创建了这样的文本字段:
alert.addTextFieldWithConfigurationHandler {
(tf:UITextField!) in
tf.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
}
我们有一个取消操作和一个OK操作,我们将OK操作带入禁用的世界:
(alert.actions[1] as UIAlertAction).enabled = false
随后,除非文本字段中有实际文字,否则用户无法点击确定:
func textChanged(sender:AnyObject) {
let tf = sender as UITextField
var resp : UIResponder = tf
while !(resp is UIAlertController) { resp = resp.nextResponder() }
let alert = resp as UIAlertController
(alert.actions[1] as UIAlertAction).enabled = (tf.text != "")
}
编辑以上代码的当前版本(Swift 3.0.1及更高版本):
alert.addTextField { tf in
tf.addTarget(self, action: #selector(self.textChanged), for: .editingChanged)
}
和
alert.actions[1].isEnabled = false
和
@objc func textChanged(_ sender: Any) {
let tf = sender as! UITextField
var resp : UIResponder! = tf
while !(resp is UIAlertController) { resp = resp.next }
let alert = resp as! UIAlertController
alert.actions[1].isEnabled = (tf.text != "")
}
答案 1 :(得分:13)
我已经简化了亚马的答案,而没有观察层次结构。这将把动作本身作为一个弱变量。这是一个完全有效的例子:
weak var actionToEnable : UIAlertAction?
func showAlert()
{
let titleStr = "title"
let messageStr = "message"
let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.Alert)
let placeholderStr = "placeholder"
alert.addTextFieldWithConfigurationHandler({(textField: UITextField) in
textField.placeholder = placeholderStr
textField.addTarget(self, action: "textChanged:", forControlEvents: .EditingChanged)
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (_) -> Void in
})
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: { (_) -> Void in
let textfield = alert.textFields!.first!
//Do what you want with the textfield!
})
alert.addAction(cancel)
alert.addAction(action)
self.actionToEnable = action
action.enabled = false
self.presentViewController(alert, animated: true, completion: nil)
}
func textChanged(sender:UITextField) {
self.actionToEnable?.enabled = (sender.text! == "Validation")
}
答案 2 :(得分:6)
克服@Matt的答案,这里是我在Obj-C中做同样事情的方式
- (BOOL)textField: (UITextField*) textField shouldChangeCharactersInRange: (NSRange) range replacementString: (NSString*)string
{
NSString *newString = [textField.text stringByReplacingCharactersInRange: range withString: string];
// check string length
NSInteger newLength = [newString length];
BOOL okToChange = (newLength <= 16); // don't allow names longer than this
if (okToChange)
{
// Find our Ok button
UIResponder *responder = textField;
Class uiacClass = [UIAlertController class];
while (![responder isKindOfClass: uiacClass])
{
responder = [responder nextResponder];
}
UIAlertController *alert = (UIAlertController*) responder;
UIAlertAction *okAction = [alert.actions objectAtIndex: 0];
// Dis/enable Ok button based on same-name
BOOL duplicateName = NO;
// <check for duplicates, here>
okAction.enabled = !duplicateName;
}
return (okToChange);
}
答案 3 :(得分:2)
我意识到这是在Objectiv-C中,但它显示了主体。稍后我会用swift版本更新它。
您也可以使用块作为目标。
向ViewController
添加一个属性,以便该块(swift的闭包)具有强大的引用
@property (strong, nonatomic) id textValidationBlock;
然后像这样创建AlertViewController
:
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
__weak typeof(self) weakSelf = self;
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
[weakSelf doSomething];
}];
[alertController addAction:cancelAction];
[alertController addAction:okAction];
[alertController.actions lastObject].enabled = NO;
self.textValidationBlock = [^{
UITextField *textField = [alertController.textFields firstObject];
if (something) {
alertController.message = @"Warning message";
[alertController.actions lastObject].enabled = NO;
} else if (somethingElse) {
alertController.message = @"Another warning message";
[alertController.actions lastObject].enabled = NO;
} else {
//Validation passed
alertController.message = @"";
[alertController.actions lastObject].enabled = YES;
}
} copy];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.placeholder = @"placeholder here";
[textField addTarget:weakSelf.textValidationBlock action:@selector(invoke) forControlEvents:UIControlEventEditingChanged];
}];
[self presentViewController:alertController animated:YES completion:nil];
答案 4 :(得分:0)
这与其他答案中的想法相同,但是我希望在扩展名中隔离一个简单的方法,并可以在任何UIViewController子类中使用。它显示一个带有一个文本输入字段和两个按钮的警报:“确定”和“取消”。
extension UIViewController {
func askForTextAndConfirmWithAlert(title: String, placeholder: String, okHandler: @escaping (String?)->Void) {
let alertController = UIAlertController(title: title, message: nil, preferredStyle: .alert)
let textChangeHandler = TextFieldTextChangeHandler { text in
alertController.actions.first?.isEnabled = !(text ?? "").isEmpty
}
var textHandlerKey = 0
objc_setAssociatedObject(self, &textHandlerKey, textChangeHandler, .OBJC_ASSOCIATION_RETAIN)
alertController.addTextField { textField in
textField.placeholder = placeholder
textField.clearButtonMode = .whileEditing
textField.borderStyle = .none
textField.addTarget(textChangeHandler, action: #selector(TextFieldTextChangeHandler.onTextChanged(sender:)), for: .editingChanged)
}
let okAction = UIAlertAction(title: CommonLocStr.ok, style: .default, handler: { _ in
guard let text = alertController.textFields?.first?.text else {
return
}
okHandler(text)
objc_setAssociatedObject(self, &textHandlerKey, nil, .OBJC_ASSOCIATION_RETAIN)
})
okAction.isEnabled = false
alertController.addAction(okAction)
alertController.addAction(UIAlertAction(title: CommonLocStr.cancel, style: .cancel, handler: { _ in
objc_setAssociatedObject(self, &textHandlerKey, nil, .OBJC_ASSOCIATION_RETAIN)
}))
present(alertController, animated: true, completion: nil)
}
}
class TextFieldTextChangeHandler {
let handler: (String?)->Void
init(handler: @escaping (String?)->Void) {
self.handler = handler
}
@objc func onTextChanged(sender: AnyObject) {
handler((sender as? UITextField)?.text)
}
}