如何将第二模态视图的文本域值获取到第一模态视图的文本域

时间:2012-08-16 04:32:15

标签: iphone ios xcode ios5

  

可能重复:
  Passing Data between View Controllers

我有2个模态视图。第一个模态视图用于编辑数量和价格;当我们点击第一个模态视图的价格文本字段时,使用第二个模态视图,以便给出我们更改价格的原因,并且我们可以在模态视图的价格文本字段中添加新价格。当我在第二个模态视图中设置价格时,我希望第一个模态视图中的价格发生变化。如何捕捉第二模态视图的值放入第一模态视图?

4 个答案:

答案 0 :(得分:1)

使用 NSNotification 中心

您必须在第一次模态视图

中添加addobserver事件
    -(void)viewWillAppear:(BOOL)animated
    {
        [super viewWillAppear:animated];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload:) name:@"refresh" object:nil];
    }
- (void)reload:(NSNotification *)notification {
    textfield.text= [[notification userInfo] valueForKey:@"price"] ;
}

第二次模​​态视图中,您必须在完成修改后发布通知

(传递你的文本字段值)

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"333" forKey:@"price"];
   [[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:nil userInfo:userInfo]

最后删除观察者

-

(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"refresh" object:nil];

}

答案 1 :(得分:0)

您可以使用 Singleton 来保存该类的一些数据

答案 2 :(得分:0)

以下简单步骤将使您能够执行此操作。

在第一个Modal ViewController中,您可以声明类似

的函数
- (void) setUpdatedValueWithValue: (NSString *) newValue
{
    self.objTextField.text  =  newValue;
}

也在头文件上声明此函数,以便我们可以从其他类访问它。

在第二个Modal ViewController中

<强> SecondViewController.h

@interface SecondViewController : UIViewController
{
     id    objFirstViewController;
}
@property (nonatomic, retain)   id   objFirstViewController;

@end

<强> SecondViewController.m

@implementation SecondViewController

@synthesize objFirstViewController;

@end

在您展示SecondViewController之前,将FirstViewController的对象传递给SecondViewController

- (void) presentSecondViewController
{
    SecondViewController    *objSecondViewController  =  [[SecondViewController alloc] init];
    objSecondViewController.objFirstViewController    =  self;
    [self presentModalViewController: objSecondViewController animated: YES];
    [objSecondViewController release];
    objSecondViewController = nil;
}

然后,在您可以执行的值编辑后,您要调用的函数将忽略SecondViewController

- (void) finishEdit
{
    if([objFirstViewController respondsToSelector: @selector(setUpdatedValueWithValue:)])
    {
        [objFirstViewController performSelector: @selector(setUpdatedValueWithValue:) withObject: editedTextView.text];
    }
    [self dismissModalViewControllerAnimated: YES];     
}

希望这有帮助。

答案 3 :(得分:-1)

使用关键字设置对象

[[NSUserDefaults standardUserDefaults]setObject:@"value of second modal view" forKey:@"keyName"];

比在第一个模态视图中获取该对象

NSString *name = [[NSUserDefaults standardUserDefaults]objectForKey:@"keyName"];