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

时间:2011-06-12 00:41:40

标签: iphone ios

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

13 个答案:

答案 0 :(得分:264)

在iOS 5中,有一种新的 easy 方式。我不确定实现是否完全完整,因为它不是一个优雅的,比如说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];

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

example alert with alertViewStyle set to UIAlertViewStylePlainTextInput

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

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

这里我只是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];

这会产生此警报:

UIAlertView that uses the UIAlertViewPlainTextInput alertStyle to ask a user name

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

玩得开心!

答案 1 :(得分:181)

要确保在用户输入文本后收到回调,请在配置处理程序中设置委托。 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)

在Swift(iOS 8-10)中:

enter image description here

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)
}

在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];
}

适用于iOS 5-7:

UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];

enter image description here


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

只是添加另一个版本。

UIAlert With UITextField

- (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];

}

然后我在需要时拨打[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) {
        ...

    }
}

答案 2 :(得分: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];

答案 3 :(得分:9)

由于IOS 9.0使用UIAlertController:

Height="Auto"

答案 4 :(得分:5)

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

@interface YourViewController : UIViewController <UIAlertViewDelegate>

你也可以找到一个非常有用的教程here

希望这有帮助。

答案 5 :(得分: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;
}

答案 6 :(得分:3)

斯威夫特3:

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:"
})

self.present(alert, animated: true, completion: nil)

答案 7 :(得分:2)

我会使用带有UIAlertView子视图的UITextField。您可以手动添加文本字段,也可以在iOS 5中使用其中一种新方法。

答案 8 :(得分:2)

将视图添加到像this这样的UIAlertView。在iOS 5中有一些“神奇”的东西可以为你做(但这都是在NDA下)。

答案 9 :(得分:2)

在Xamarin和C#中:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();

答案 10 :(得分:0)

基于John Riselvato的答案,从UIAlertView中取回字符串...

awk 'BEGIN{FS=OFS=";"} {val=$1;sub(";","@@@");gsub(";",ORS val ";");sub("@@@",";",$1)} 1' Input_file

答案 11 :(得分:0)

Final output when you call the function below

对于 Swift 5.1:(更新之前的答案)

 \begin{figure*}[ht!]
        \centering
            \subfigure[] 
            {
                \label{subfig:lab1}
                \includegraphics[width=.3\textwidth]{figures/1.pdf} % .png .jpg ... according to supported graphics files
            } 
            %
            \subfigure[] 
            {
                \label{subfig:lab2}
                \includegraphics[width=.3\textwidth]{figures/2.pdf} % .png .jpg ... according to supported graphics files
            }
            %
            \subfigure[] 
            {
                \label{subfig:lab3}
                \includegraphics[width=.3\textwidth]{figures/3.pdf} % .png .jpg ... according to supported graphics files
            }\\ % for new row or line of subfigures
            %
            \subfigure[Caption 4] 
            {
                \label{subfig:lab4}
                \includegraphics[width=.3\textwidth]{figures/4.pdf} % .png .jpg ... according to supported graphics files
            }
            %
            \subfigure[Caption 5] 
            {
                \label{subfig:lab6}
                \includegraphics[width=.3\textwidth]{figures/5.pdf} % .png .jpg ... according to supported graphics files
            }
            %
            \subfigure[Caption 6] 
            {
                \label{subfig:lab6}
                \includegraphics[width=.3\textwidth]{figures/6.pdf} % .png .jpg ... according to supported graphics files 
            }
            %
        \caption{Figure Caption}
        \label{fig:Figure ref}
        \end{figure*}

答案 12 :(得分:-1)

UIAlertview *alt = [[UIAlertView alloc]initWithTitle:@"\n\n\n" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];

UILabel *lbl1 = [[UILabel alloc]initWithFrame:CGRectMake(25,17, 100, 30)];
lbl1.text=@"User Name";

UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(25, 60, 80, 30)];
lbl2.text = @"Password";

UITextField *username=[[UITextField alloc]initWithFrame:CGRectMake(130, 17, 130, 30)];
UITextField *password=[[UITextField alloc]initWithFrame:CGRectMake(130, 60, 130, 30)];

lbl1.textColor = [UIColor whiteColor];
lbl2.textColor = [UIColor whiteColor];

[lbl1 setBackgroundColor:[UIColor clearColor]];
[lbl2 setBackgroundColor:[UIColor clearColor]];

username.borderStyle = UITextBorderStyleRoundedRect;
password.borderStyle = UITextBorderStyleRoundedRect;

[alt addSubview:lbl1];
[alt addSubview:lbl2];
[alt addSubview:username];
[alt addSubview:password];

[alt show];