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

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

160304 次浏览

我会使用一个 UIAlertView与一个 UITextField子视图。您可以手动添加文本字段,或者在 iOS5中使用其中一种新方法。

将视图添加到 UIAlertView,如 这个。在 iOS5中,有一些“神奇”的东西可以为你做到这一点(但这些都属于保密协议)。

在 iOS5中有一种新的和 放松的方法。我不确定这个实现是否已经完成,因为它不像 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这一个) ,直到正确的输入输入。

玩得开心!

测试了 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];

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

目标-C (iOS8) :

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


注意: 以下内容不适用于 iOS7(iOS4-6可用)

再加一个版本。

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) {
...


}
}

我只是想补充一条重要的信息,我相信这条信息可能被遗漏了,因为那些寻求答案的人可能已经知道了。这个问题经常发生,当我试图为 UIAlertView消息的按钮实现 viewAlert方法时,我也发现自己卡住了。要做到这一点,您需要首先添加委托类,它可能看起来像下面这样:

@interface YourViewController : UIViewController <UIAlertViewDelegate>

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

希望这个能帮上忙。

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

由于 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];

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

在 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();

斯威夫特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)

基于 John Riselvato 的回答,从 UIAlertView 检索回字符串..。

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
guard let message = alert.textFields?.first?.text else {
return
}
// Text Field Response Handling Here
})

Final output when you call the function below

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

func doAlertControllerDemo() {
        

var inputTextField: UITextField?;
let passwordPrompt = UIAlertController(title: "Enter Password", message: "You have selected to enter your password.", preferredStyle: UIAlertController.Style.alert);
    

passwordPrompt.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.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.doAlertControllerDemo(); //do again!
}));
    

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

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

self.present(passwordPrompt, animated: true, completion: nil);
return;
}