gpt4 book ai didi

iphone - 从 UIAlertView 获取文本

转载 作者:太空狗 更新时间:2023-10-30 03:15:11 26 4
gpt4 key购买 nike

我正在尝试从警报 View 中获取文本并将其添加到我的可变数组中以在 TableView 中列出。我意识到几个月前发布了一个类似的问题,但我不明白如何利用给定的答案。

-(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 对象。我做错了什么?

编辑:好的,我想我缺少一种处理警报 View 的方法。所以我发现了这个:

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

}

现在我只需要连接各个部分,但不确定如何连接。

最佳答案

人们在使用 UIAlertView 时常犯的一个错误是他们认为向它发送 show 消息会阻塞主线程。它不是。您的代码继续执行,即使屏幕上有警告。因此,您传入的 UITextField 不存在任何值。

您需要做的是在您的 UIViewController 中实现 UIAlertViewDelegate 以获取用户在文本字段中输入的任何内容。也就是说,您仍然需要检查 nil 值,因为如果您不输入任何内容,text 值将为 nil .

更新:此答案是在 Apple 创建用于通过 UIAlertViewStyle 向警报添加 UITextField 的 API 之前发布的。这是更新后的代码,借自@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"
}
}

关于iphone - 从 UIAlertView 获取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4560346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com