两个ViewController间传值(二)

 这次要讲的是如何从A进入B,在B输入值后回传给A,那么在IOS中实现这个功能就需要使用到Delegate(委托协议)。

其中有两个ViewController分别对应两个界面,一个协议PassValueDelegate用来实现传值协议,UserEntity是传递数据的对象。

协议中声明的方法:

#import <Foundation/Foundation.h>  
@class UserEntity;  
  
@protocol PassValueDelegate <NSObject>  
  
-(void)passValue:(UserEntity *)value;  
  
@end  

 在第一个窗口实现协议:

//第一个窗口遵守PassValueDelegate  
@interface ViewController : UIViewController<PassValueDelegate>  
  
@property (retain, nonatomic) IBOutlet UILabel *nameLabel;  
@property (retain, nonatomic) IBOutlet UILabel *ageLabel;  
@property (retain, nonatomic) IBOutlet UILabel *gendarLabel;  
  
- (IBAction)openBtnClicked:(id)sender;  
  
@end  

 .m文件中实现协议的方法

//实现协议,在第一个窗口显示在第二个窗口输入的值
-(void)passValue:(UserEntity *)value  
{  
    self.nameLabel.text = value.userName;  
    self.ageLabel.text = [NSString stringWithFormat:@"%d",value.age];  
    self.gendarLabel.text = value.gendar;
}

 点击按钮所触发的事件:

//点击进入第二个窗口的方法  
- (IBAction)openBtnClicked:(id)sender {  
    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:[NSBundle mainBundle]];  
    //设置第二个窗口中的delegate为第一个窗口的self  
    secondView.delegate = self;  
      
    [self.navigationController pushViewController:secondView animated:YES];  
    [secondView release];  
}  

第二个窗口中声明一个NSObject对象,该对象遵守PassValueDelegate协议:

@interface SecondViewController : UIViewController  
  
@property (retain, nonatomic) IBOutlet UITextField *nameTextField;  
@property (retain, nonatomic) IBOutlet UITextField *ageTextFiled;  
@property (retain, nonatomic) IBOutlet UITextField *gendarTextField;  
  
//这里用assign而不用retain是为了防止引起循环引用。  
@property(nonatomic,assign) NSObject<PassValueDelegate> *delegate;  
  
- (IBAction)okBtnClicked:(id)sender;  
- (IBAction)closeKeyboard:(id)sender;  
  
@end  

  输入完毕后,点击按钮所触发的事件:

- (IBAction)okBtnClicked:(id)sender {  
    UserEntity *userEntity = [[UserEntity alloc] init];  
    userEntity.userName = self.nameTextField.text;  
    userEntity.gendar = self.gendarTextField.text;  
    userEntity.age = [self.ageTextFiled.text intValue];  
      
    //通过委托协议传值  
    [self.delegate passValue:userEntity];  
    //退回到第一个窗口  
    [self.navigationController popViewControllerAnimated:YES];  
      
    [userEntity release];  
}  

 

猜你喜欢

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