ios 在 iPhone 上获取文本输入弹出对话框的简单方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6319417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's a simple way to get a text input popup dialog box on an iPhone
提问by user605957
I want to get the user name. A simple text input dialog box. Any simple way to do this?
我想获取用户名。一个简单的文本输入对话框。有什么简单的方法可以做到这一点?
回答by Warkst
In iOS 5 there is a new and easyway to this. I'm not sure if the implementation is fully complete yet as it's not a gracious as, say, a UITableViewCell
, but it should definitly do the trick as it is now standard supported in the iOS API. You will not need a private API for this.
在 iOS 5 中,有一种新的、简单的方法可以做到这一点。我不确定实现是否已经完全完成,因为它不像 a 那样亲切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];
This renders an alertView like this (screenshot taken from the iPhone 5.0 simulator in XCode 4.2):
这会呈现一个这样的警报视图(从 XCode 4.2 中的 iPhone 5.0 模拟器截取的屏幕截图):
When pressing any buttons, the regular delegate methods will be called and you can extract the textInput there like so:
当按下任何按钮时,将调用常规委托方法,您可以像这样提取 textInput :
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
NSLog(@"Entered: %@",[[alertView textFieldAtIndex:0] text]);
}
Here I just NSLog the results that were entered. In production code, you should probably keep a pointer to your alertView as a global variable or use the alertView tag to check if the delegate function was called by the appropriate UIAlertView
but for this example this should be okay.
这里我只是 NSLog 输入的结果。在生产代码中,您可能应该将指向 alertView 的指针保留为全局变量,或者使用 alertView 标记来检查委托函数是否被适当的调用,UIAlertView
但对于本示例,这应该没问题。
You should check out the UIAlertView APIand you'll see there are some more styles defined.
您应该查看UIAlertView API,您会看到定义了更多样式。
Hope this helped!
希望这有帮助!
-- EDIT --
- 编辑 -
I was playing around with the alertView a little and I suppose it needs no announcement that it's perfectly possible to edit the textField as desired: you can create a reference to the UITextField
and edit it as normal (programmatically).
Doing this I constructed an alertView as you specified in your original question. Better late than never, right :-)?
我稍微玩弄了 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];
This produces this alert:
这会产生此警报:
You can use the same delegate method as I poster earlier to process the result from the input. I'm not sure if you can prevent the UIAlertView
from dismissing though (there is no shouldDismiss
delegate function AFAIK) so I suppose if the user input is invalid, you have to put up a new alert (or just reshow
this one) until correct input was entered.
您可以使用与我之前发布的相同的委托方法来处理输入的结果。我不确定你是否可以阻止UIAlertView
解除(没有shouldDismiss
委托函数 AFAIK)所以我想如果用户输入无效,你必须提出一个新的警报(或者只是show
这个),直到正确的输入是进入。
Have fun!
玩得开心!
回答by John Riselvato
To make sure you get the call backs after the user enters text, set the delegate inside the configuration handler. textField.delegate = self
为确保在用户输入文本后获得回调,请在配置处理程序中设置委托。 textField.delegate = self
Swift 3 & 4 (iOS 10 - 11):
斯威夫特 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)
In Swift (iOS 8-10):
在 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)
}
In Objective-C (iOS 8):
在 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];
}
FOR iOS 5-7:
对于 iOS 5-7:
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"INPUT BELOW" delegate:self cancelButtonTitle:@"Hide" otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
NOTE: Below doesn't work with iOS 7 (iOS 4 - 6 Works)
注意:以下不适用于 iOS 7(iOS 4 - 6 Works)
Just to add another version.
只是为了添加另一个版本。
- (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];
}
then I call [alert show];
when I want it.
然后我[alert show];
在需要的时候打电话。
The method that goes along
伴随的方法
- (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) {
...
}
}
回答by funroll
Tested out Warkst's third code snippet--worked great, except I changed it to be default input type instead of numeric:
测试了 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];
回答by EckhardN
Since IOS 9.0 use UIAlertController:
由于 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];
回答by J-Dizzle
Try this Swift code in a UIViewController -
在 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;
}
回答by Jason Lambert
Just wanted to add an important piece of information that I believe was left out perhaps with the assumption that the ones seeking answers might already know. This problem happens a lot and I too found myself stuck when I tried to implement the viewAlert
method for the buttons of the UIAlertView
message. To do this you need to 1st add the delegate class which may look something like this:
只是想添加一条我认为被遗漏的重要信息,可能是假设寻求答案的人可能已经知道。这个问题经常发生,当我尝试实现消息viewAlert
按钮的方法时,我也发现自己卡住了UIAlertView
。为此,您需要首先添加可能如下所示的委托类:
@interface YourViewController : UIViewController <UIAlertViewDelegate>
@interface YourViewController : UIViewController <UIAlertViewDelegate>
Also you can find a very helpful tutorial here!
你也可以在这里找到一个非常有用的教程!
Hope this helps.
希望这可以帮助。
回答by Daniil Chuiko
Swift 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)
回答by Bj?rn Egil
In Xamarin and C#:
在 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();
回答by Alexsander Akers
I would use a UIAlertView
with a UITextField
subview. You can either add the text field manually or, in iOS 5, use one of the new methods.
我会使用UIAlertView
带有UITextField
子视图的a 。您可以手动添加文本字段,也可以在 iOS 5 中使用其中一种新方法。