在iPhone上获取文本输入弹出对话框的简单方法是什么

use*_*957 123 iphone ios

我想获取用户名.一个简单的文本输入对话框.有什么简单的方法吗?

War*_*kst 264

在iOS 5中,有一种新的简单方法.我不确定实现是否完全完整,因为它不是一个优雅的,比方说UITableViewCell,但它应该明确地做,因为它现在是iOS API中的标准支持.您不需要私有API.

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"This is an example alert!" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
[alert release];
Run Code Online (Sandbox Code Playgroud)

这将呈现这样的alertView(截图取自XCode 4.2中的iPhone 5.0模拟器):

alertViewStyle设置为UIAlertViewStylePlainTextInput的示例警报

当按下任何按钮时,将调用常规委托方法,您可以像这样提取textInput:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    NSLog(@"Entered: %@",[[alertView textFieldAtIndex:0] text]);
}
Run Code Online (Sandbox Code Playgroud)

在这里,我只是NSLog输入的结果.在生产代码中,您可能应该将指向alertView的指针保存为全局变量,或者使用alertView标记来检查委托函数是否被相应的调用,UIAlertView但对于此示例,这应该没问题.

您应该查看UIAlertView API,您将看到定义了更多样式.

希望这有帮助!

- 编辑 -

我正在使用alertView一点点,我想它不需要声明完全可以根据需要编辑textField:你可以创建一个引用UITextField并正常编辑它(以编程方式).这样做我构建了一个你在原始问题中指定的alertView.迟到总比不到好,对吧 :-)?

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeNumberPad;
alertTextField.placeholder = @"Enter your name";
[alert show];
[alert release];
Run Code Online (Sandbox Code Playgroud)

这会产生此警报:

UIAlertView使用UIAlertViewPlainTextInput alertStyle来询问用户名

您可以使用与我前面提到的相同的委托方法来处理输入中的结果.我不确定你是否可以阻止UIAlertView解散(没有shouldDismiss代理功能AFAIK)所以我想如果用户输入无效,你必须提出一个新的警报(或只是重新show这个),直到正确的输入是进入.

玩得开心!

  • 我知道,但这个答案写于2011年. (5认同)
  • 自IOS 9.0起,该方法已折旧.请改用UIAlertController: (3认同)

Joh*_*ato 183

要确保在用户输入文本后收到回调,请在配置处理程序中设置委托. textField.delegate = self

Swift 3&4(iOS 10 - 11):

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
    textField.placeholder = "Enter text:"
    textField.isSecureTextEntry = true // for password input
})
self.present(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

在Swift(iOS 8-10)中:

在此输入图像描述

override func viewDidAppear(animated: Bool) {
    var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil))
    alert.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Enter text:"
        textField.secureTextEntry = true
        })
    self.presentViewController(alert, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

在Objective-C(iOS 8)中:

- (void) viewDidLoad 
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"Click" style:UIAlertActionStyleDefault handler:nil]];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"Enter text:";
        textField.secureTextEntry = YES;
    }];
    [self presentViewController:alert animated:YES completion:nil];
}
Run Code Online (Sandbox Code Playgroud)

对于iOS 5-7:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


注意:以下不适用于iOS 7(iOS 4 - 6 Works)

只是添加另一个版本.

使用UITextField进行UIAlert

- (void)viewDidLoad{

    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Preset Saving..." message:@"Describe the Preset\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    UITextField *textField = [[UITextField alloc] init];
    [textField setBackgroundColor:[UIColor whiteColor]];
    textField.delegate = self;
    textField.borderStyle = UITextBorderStyleLine;
    textField.frame = CGRectMake(15, 75, 255, 30);
    textField.placeholder = @"Preset Name";
    textField.keyboardAppearance = UIKeyboardAppearanceAlert;
    [textField becomeFirstResponder];
    [alert addSubview:textField];

}
Run Code Online (Sandbox Code Playgroud)

然后我打电话给[alert show];我.

随之而来的方法

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {         
    NSString* detailString = textField.text;
    NSLog(@"String is: %@", detailString); //Put it on the debugger
    if ([textField.text length] <= 0 || buttonIndex == 0){ 
        return; //If cancel or 0 length string the string doesn't matter
    }
    if (buttonIndex == 1) {
        ...

    }
}
Run Code Online (Sandbox Code Playgroud)


fun*_*oll 11

测试了Warkst的第三个代码片段 - 工作得很好,除了我将其更改为默认输入类型而不是数字:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Hello!" message:@"Please enter your name:" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeDefault;
alertTextField.placeholder = @"Enter your name";
[alert show];
Run Code Online (Sandbox Code Playgroud)


Eck*_*rdN 10

由于IOS 9.0使用UIAlertController:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                                                           message:@"This is an alert."
                                                          preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * action) {
                    //use alert.textFields[0].text
                                                       }];
UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action) {
                                                          //cancel action
                                                      }];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
    // A block for configuring the text field prior to displaying the alert
}];
[alert addAction:defaultAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)


小智 5

只是想添加一条我认为遗漏的重要信息,或许假设寻求答案的人可能已经知道了.这个问题发生了很多,当我试图实现消息viewAlert按钮的方法时,我也发现自己陷入困境UIAlertView.要做到这一点,你需要首先添加委托类,它可能看起来像这样:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

你也可以在这里找到一个非常有用的教程!

希望这可以帮助.


J-D*_*zle 5

在UIViewController中尝试这个Swift代码 -

func doAlertControllerDemo() {

    var inputTextField: UITextField?;

    let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your passwod.", preferredStyle: UIAlertControllerStyle.Alert);

    passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        // Now do whatever you want with inputTextField (remember to unwrap the optional)

        let entryStr : String = (inputTextField?.text)! ;

        print("BOOM! I received '\(entryStr)'");

        self.doAlertViewDemo(); //do again!
    }));


    passwordPrompt.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
        print("done");
    }));


    passwordPrompt.addTextFieldWithConfigurationHandler({(textField: UITextField!) in
        textField.placeholder = "Password"
        textField.secureTextEntry = false       /* true here for pswd entry */
        inputTextField = textField
    });


    self.presentViewController(passwordPrompt, animated: true, completion: nil);


    return;
}
Run Code Online (Sandbox Code Playgroud)