所以我有一个UIAlertView有两个按钮和一个TextField,我的问题是我想保存用户在文本字段中输入的文本保存到我在核心数据中的字符串“name”。我的所有核心数据编程都是正确的,我在UITextField中使用它而不是一个在alertview上。我只是不知道如何保存用户输入UIAlertView的TextField的内容。如果有人可以帮助我,我们将不胜感激。
以下是我的提醒视图:http://gyazo.com/8eba23f1fb1f5fbe49738af9185e689f
我的UIAlertView代码:
- (IBAction)button:(id)sender {
Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add List" message:@"Create a New Wish List" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Save", nil];
[alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
[alert setTag:2];
[alert show];
NSError *error = nil;
if (![_managedObjectContext save:&error]) {
//Handle
}
答案 0 :(得分:0)
您需要使用UIAlertViewDelegate
在警报视图中捕获来自UITextField的用户输入。
让我们告诉UIAlertView您将使用该委托,如下所示:
UIAlertView *alert = ...;
//other UIAlertView settings here
alert.delegate = self;
接下来,在代码中实现以下委托方法:
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if ([buttonIndex != 0 && alertView.tag == 2) {
NSString *name = [alertView textFieldAtIndex:0].text;
}
}
当然,为了调用委托方法,您还需要符合头文件中的委托:
@interface CustomViewController : UIViewController <UIAlertViewDelegate>
答案 1 :(得分:0)
调用委托方法时,需要从文本字段中提取字符串。
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
UITextField *tf = [alertView textFieldAtIndex:0];
Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];
lists.name =tf.text;
// save to core data
}
答案 2 :(得分:0)
试试这个:
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];
if (buttonIndex != 0 && alertView.tag == 2) {
NSString *name = [alertView textFieldAtIndex:0].text;
UITextField *tf = [alertView textFieldAtIndex:0];
list.name =tf.text;
}
{
NSError *error = nil;
if (![_managedObjectContext save:&error]){
Handle;
}
}
}