我正在尝试从一个警报视图中获取文本,并将其添加到我的可变数组中,以便在表视图中列出。我意识到几个月前发布了一个类似的问题,但我不明白如何利用给定的答案。
-(IBAction)insert {
UIAlertView* dialog = [[UIAlertView alloc] init];
[dialog setDelegate:self];
[dialog setTitle:@"Enter Name"];
[dialog setMessage:@" "];
[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];
[dialog show];
[data addObject:[nameField text]];
[mainTableView reloadData];
然而,我的应用程序崩溃了,因为它显示我正试图在索引0处插入一个nil对象。我做错了什么?
编辑:好的,我想我缺少一个处理警报视图的方法。所以我发现了这个:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *buttonTitle=[alertView buttonTitleAtIndex:buttonIndex];
if([buttonTitle isEqualToString:@"Cancel"]) {
return;
}
else if([buttonTitle isEqualToString:@"Ok"]) {
[data addObject:nameField.text];
}
现在我只需要将这些部分连接起来,但不确定如何连接。
发布于 2010-12-30 14:16:40
人们在使用UIAlertView
时经常犯的一个错误是,他们认为向它发送show
消息会阻塞主线程。事实并非如此。即使屏幕上有警告,您的代码也会继续执行。因此,您传入的UITextField
不存在任何值。
您需要做的是在UIViewController
中实现UIAlertViewDelegate
,以获取用户在文本字段中输入的内容。也就是说,您仍然需要检查nil
值,因为如果不键入任何内容,则text
值将为nil
。
更新:这个答案是在苹果开发出通过UIAlertViewStyle
向警报添加UITextField
的应用程序接口之前发布的。以下是更新后的代码,从@matt借用
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Name"
message:@" "
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
然后,在UIAlertViewDelegate
回调中:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *name = [alertView textFieldAtIndex:0].text;
// Insert whatever needs to be done with "name"
}
}
发布于 2012-01-11 05:00:34
您不需要将自己的文本字段添加到AlertView中,而是设置适当的样式
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Name"
message:@" "
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OK", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
然后在按下OK (按钮1)后访问输入的文本
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
NSString *name = [alertView textFieldAtIndex:0].text;
// name contains the entered value
}
}
发布于 2010-12-30 14:15:10
– alertView:clickedButtonAtIndex:
是UIAlertView的一个委托方法。只需将您在编辑中定义的方法添加到您的控制器实现中,就可以了,因为您已经将控制器设置为AlertView的委托。
还要添加到你的类头中,以避免任何与委托相关的警告,例如:
@interface MyViewController : UIViewController <UIAlertViewDelegate> {
...
};
不要忘记从insert方法中删除[data addObject:[nameField text]];
和[mainTableView reloadData];
。
https://stackoverflow.com/questions/4560346
复制相似问题