两个ViewController间传值(一)

其中ViewController是第一个界面,SecondViewController是第二个界面,UserEntity为一个实体对象,用来作为在两个界面间传值的媒介。

在第一个界面输入完毕后,点击“传值“按钮就可以跳转到第二个界面,并显示在第一个界面中输入的值,按顶部的Back按钮则返回第一个界面。

下面来看看实现中的关键代码;

单击”传值“按钮时触发的代码:

- (IBAction)passValueButton:(id)sender {  
    //构建UserEntity对象  
    UserEntity *userEntity = [[UserEntity alloc] init];  
    userEntity.userName = self.userNameTextFiled.text;  
    userEntity.gendar = self.gendarTextField.text;  
    userEntity.age = [self.ageTextField.text intValue];  
      
    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];  
    //设置SecondViewController中的值  
    secondView.userEntity = userEntity;  
    //跳转界面  
    [self presentModalViewController:secondView animated:YES];  
      
    [userEntity release];  
    [secondView release];  
}  

在第二个界面显示传过来值的方法:

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
      
    //显示从前一个界面传过来的值  
    self.userNameTextField.text = self.userEntity.userName;  
    self.gendarTextField.text = self.userEntity.gendar;  
    //NSString转换为int型  
    self.ageTextField.text = [NSString stringWithFormat:@"%d",self.userEntity.age];  
      
}  

  以上就实现了一个简单的在两个ViewController之间传值的方式。

猜你喜欢

转载自1395014506.iteye.com/blog/2246630