将数据从一个视图控制器传输到另一个视图控制器

时间:2015-03-07 21:21:39

标签: ios iphone button transfer

如果我在第一个视图控制器中填写州,省和镇,当我按下OK按钮时,如何在另一个视图控制器中获得城镇或城镇状态。

http://i.stack.imgur.com/jhwGq.png

2 个答案:

答案 0 :(得分:0)

首先,您应该在SecondVC.h中创建一个属性来接收de text和链接到屏幕中标签的属性:

@property(nonatomic, copy) NSString *townText;
@property (weak, nonatomic) IBOutlet UILabel *townLabel;

之后,在SecondVC.m中,覆盖" viewWillAppear"方法如下:

- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
self.townLabel.text = self.townText;

}

然后,在FirstVC.m中,覆盖" prepareForSegue"方法:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
SecondVC *secondVC = segue.destinationViewController;
secondVC.townText = self.townTextView.text; // townTextView is the TextView in screen where user writes the town name.

}

不要忘记在FirstVC.m中导入SecondVC.h

答案 1 :(得分:-1)

简单方法:

 Use storyboard's IBOutlet feature. One view controller class can hold a reference to another view controller
 If the code just reference the other view controller
 -(void)clickOK:(UIButton*)
 {
      NSString* town = self.anotherController;
      //do something with town
 }

建议方式:      遵循模型 - 视图 - 控制器设计模式。将第一个视图控制器视为数据提供者

Protocal DataProviderDelegate
{
   @required
   -(NSString*)getTown;
   -(NSString*)getState;
} 

 @implementation
  FirstViewController:UIViewController<DataProviderDelegate>
 {

 }

 @declaration
 SecondViewController:UIViewController
 @property(nonatomic, weak)DataProviderDelegate* dataProvider;

在segue中,将第一个视图控制器指定给第二个视图控制器作为委托