[英]How do I get text from UITextField in an UIAlertView
我正在尝试向tableview添加一个新单元格,并使用UITextField弹出一个警报,以允许用户输入他们希望为新单元格提供的标题。 我有代码在按下“+”按钮时用UITextField弹出警报,以及添加新单元格的代码,但是我不知道如何从UITextField获取文本以将其插入到单元格的标题中。
这是我弹出警报的代码:
UIAlertView* alertPopUp = [[UIAlertView alloc] init];
[alertPopUp setDelegate:self];
[alertPopUp setTitle:@"Enter event title"];
[alertPopUp setMessage:@" "];
[alertPopUp addButtonWithTitle:@"Cancel"];
[alertPopUp addButtonWithTitle:@"OK"];
UITextField * eventNameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)];
[eventNameField setBackgroundColor:[UIColor whiteColor]];
[alertPopUp addSubview:eventNameField];
[alertPopUp show];
我的alertView操作是:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Cancel"]) {
return;
}
else if([buttonTitle isEqualToString:@"Ok"]) {
}
}
当按下“确定”时,如何从eventNameField获取文本并将其添加到名为eventList的mutablearray中? 谢谢!
将eventNameField上的标记设置为有意义的内容
eventNameField.tag = 1001;
然后在alertViewDelegate里面你可以使用 - [UIView viewWithTag:]来获取TextField
UITextField* textField = (UITextField*)[alertView viewWithTag:1001];
eventNameField.text
应该为您提供值
//declare the array
NSMutableArray* eventList = [NSMutableArray array];
//set its value
[eventList addObject:eventNameField.text];
旧的答案没有利用UIAlertView的变化。
在iOS 5及更高版本中,有一种在警报视图上使用UITextfield的简便方法:
UIAlertView *alertPopUp = [[UIAlertView alloc] initWithTitle:@"Enter event title" message:@"" delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
alertPopUp.alertViewStyle = UIAlertViewStylePlainTextInput;
self.alertTextField = [message textFieldAtIndex:0];
self.alertTextField.keyboardType = UIKeyboardTypeAlphabet;
alertPopUp.delegate = self;
[alertPopUp show];
[self.alertTextField becomeFirstResponder];
alertTextField的设置方式如下:
@propery (nonatomic, strong) UITextField *alertTextField;
然后,您可以在委托响应中访问alertTextField:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Cancel"]) {
return;
}
else if([buttonTitle isEqualToString:@"Ok"]) {
NSLog(@"your text string is %@", self.alertTextField.text);
}
}
您还可以给alertView一个唯一的标记,并比较标记号,而不是使用@property保存对它的引用。
DHamrick可能有更好的解决方案,但又找到了一个可行的解决方案。
您可以使用[alertView子视图]获取alertView内的所有子视图(返回NSCFArray),然后您只需要找到UITextField类的子视图,在您的情况下,您可以使用:
[[[alertView subviews] objectAtIndex:4] text]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.