我将UITextField放入UIAlertView并将其向上移动,以便键盘不会使用以下代码覆盖它:
[dialog setDelegate:self]; [dialog setTitle:@"Enter Name"]; [dialog addButtonWithTitle:@"Cancel"]; [dialog addButtonWithTitle:@"OK"]; UITextField * nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; [nameField setBackgroundColor:[UIColor whiteColor]]; [dialog addSubview:nameField]; CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0); [dialog setTransform: moveUp]; [dialog show];
我还有以下代码来处理警报视图:
- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{ NSLog(@"%d", (int) buttonIndex); if (buttonIndex == 1) { // OK pushed NSLog([alert textField].text); // does not log anything } else { // Cancel pushed }}
我还有一个UIAlertViewExtended.h文件,其中包含:
@class UITextField, UILabel; @interface UIAlertView(Extended) -(UITextField *)textField; @end
我的问题是如何获取用户输入的文本以及如何解除键盘?
谢谢,本
任何支持iOS 5.0以及ARC的人都可以设置这个直接的alertViewStyle属性:
-(void)showAlertWithTextField{ UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil]; [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput]; // Change keyboard type [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad]; [dialog show]; } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ if (buttonIndex == 1) NSLog(@"%@",[[alertView textFieldAtIndex:0]text]); }
对于那些可能关心的人,这是一个有效的解决方案:
UIAlertView* dialog = [[UIAlertView alloc] init]; [dialog setDelegate:self]; [dialog setTitle:@"Enter Name"]; [dialog setMessage:@" "]; [dialog addButtonWithTitle:@"Cancel"]; [dialog addButtonWithTitle:@"OK"]; nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; [nameField setBackgroundColor:[UIColor whiteColor]]; [dialog addSubview:nameField]; CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0); [dialog setTransform: moveUp]; [dialog show]; [dialog release]; [nameField release];
确保你已经创建了UITextField*nameField; 在.h文件中,您可以通过执行以下操作获取用户键入的文本:inputText = [nameField text];
在 - (void)alertView:(UIAlertView*)alert clickedButtonAtIndex:(NSInteger)buttonIndex方法.
重要提示: 对于iOS 4.0+,它CGAffineTransform
会自动完成,因此如果您的目标只是4.0+,则可以将其删除.否则,您需要检查您所在的操作系统并相应地处理它.
值得一试
http://junecloud.com/journal/code/displaying-a-password-or-text-entry-prompt-on-the-iphone.html?cmd=success#comment3870
获得完整而全面的解决方案.
找到文本字段而不保留对其的明确引用的简单方法是设置其标记:
nameField.tag = ALERTVIEW_NAMEFIELD;
确保它与0和UIView
您可能拥有的其他对象标签不同,包括父对话框!
然后在alertView:clickedButtonAtIndex:
处理程序中,您可以通过以下方式检索文本字段:
UITextField *nameField = (UITextField *)[alertView viewWithTag:ALERTVIEW_NAMEFIELD];