一、在输入值的类的.h文件中声明一个到代理,并声明一个代理方法;
#import <UIKit/UIKit.h>
//声明一个AViewControllerDelegate 协议
@protocol AViewControllerDelegate<NSObject>
//@optional 为可选方法,如果不写则默认为必写方法
@optional
//声明代理方法
-(void)transValue:(NSString *)string;
@end
@interface AViewController: UIViewController
//找一个代理,并将其声明为属性
@property(nonatomic,assign)id<AViewControllerDelegate>delegate;
@end
二、在需要传值的页面的类的.m文件实现切换到输入值的页面,并实现传值方法
#import "ViewController.h"
//导入输入值的页面
#import "AViewController.h"
//遵守协议
@interface ViewController ()<AViewControllerDelegate>
//将需要传值的lable定义成属性
@property (weak, nonatomic) IBOutletUILabel *lable;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do anyadditional setup after loading the view, typically from a nib.
}
//实现点击按钮切换页面
- (IBAction)push:(id)sender {
UIStoryboard *storyboard=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
AViewController *aViewController =[storyboard instantiateViewControllerWithIdentifier:@"AViewController"];
aViewController.delegata = self;
[self presentViewController:aViewController animated:YES completion:^{
}];
}
//实现传值方法
-(void)transValue:(NSString *)string{
self.lable.text =string;
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
三、在输入值的页面的.m文件实现点击按钮回到原页面,并传值
#import "AViewController.h"
@interface AViewController ()
//定义输入值的textField为属性
@property (weak, nonatomic) IBOutlet UITextField *textField;
@end
@implementation AViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do anyadditional setup after loading the view.
}
//实现点击按钮回原页面,并传值的方法
- (IBAction)pop:(id)sender {
//判断delegate是否存在,以及是否遵守协议
if (self.delegata &&[self.delegata conformsToProtocol:@protocol(AViewControllerDelegate)]){
[self.delegata transValue:self.textField.text];
}
[selfdismissViewControllerAnimated:YES completion:^{
}];
}
- (void)didReceiveMemoryWarning{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, youwill often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender {
// Get the new viewcontroller using [segue destinationViewController].
// Pass the selectedobject to the new view controller.
}
*/
@end