【问题标题】:AlertViewController should not be dismissed when I enter empty AlertView textfield in iOS当我在 iOS 中输入空的 AlertView 文本字段时,不应关闭 AlertViewController
【发布时间】:2016-12-16 19:08:05
【问题描述】:

我在 AlertViewController 中添加了一个文本字段。我没有在文本字段中输入任何内容并输入 OK 按钮,这意味着关闭警报视图。我应该如何检查警报文本字段长度为零,以便禁用警报按钮操作。请帮帮我...

【问题讨论】:

  • 到目前为止您尝试过什么?也许您非常接近解决方案,我们会提供帮助
  • 最初你可以禁用按钮并使用 UITextFieldDelegate 方法 public func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {} 你可以禁用/启用按钮跨度>
  • 你怎么能有objective-c和swift标签?你用的是哪一个?
  • 还可以在这里查看 Guy Kahlons 的回答 stackoverflow.com/questions/24093612/… ...它可能会有所帮助

标签: ios objective-c swift xcode ios9


【解决方案1】:

试试这个代码。

//
//  ViewController.m
//  AlertControllerDemo
//
//  Created by Nilesh on 8/10/16.
//  Copyright © 2016 Nilesh. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UITextFieldDelegate>
@property(nonatomic, strong)UIAlertAction *okAction;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)showAlertButtonAction:(id)sender {

    self.okAction = [UIAlertAction actionWithTitle:@"Okay"
                                             style:UIAlertActionStyleDefault
                                           handler:nil];
    self.okAction.enabled = NO;

    UIAlertController *controller = [UIAlertController alertControllerWithTitle:nil
                                                                        message:@"Please Enter your text"
                                                                 preferredStyle:UIAlertControllerStyleAlert];

    [controller addTextFieldWithConfigurationHandler:^(UITextField *textField) {

        textField.delegate = self;
    }];

    [controller addAction:self.okAction];
    [self presentViewController:controller animated:YES completion:nil];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{

    NSString *finalString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self.okAction setEnabled:(finalString.length >= 1)];
    return YES;
}
@end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多