之前一直对于代理传值不是很了解很模糊,今天试着写了个demo,
1、在需要传值的界面声明协议,比如从B界面传值给A,那么就在B界面设置代理,然后在A界面添加代理。
在B界面:
.h文件
@protocol TwoViewDelegate <NSObject>
- (void)changeValue:(NSString *)value;
@end
@interface GCTwoViewController :
UIViewController
@property (nonatomic,unsafe_unretained)
id<TwoViewDelegate>delegate;
@end
- (IBAction)btnc:(id)sender {
[self.delegate
changeValue:self.textFiled.text];
[self
dismissViewControllerAnimated:YES
completion:nil];
}
在需要改变的界面A
#import "GCTwoViewController.h"
@interface
GCViewController ()<TwoViewDelegate>
.m文件
- (IBAction)btncli:(id)sender {
[self
performSegueWithIdentifier:@"inputTwoView"
sender:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier
isEqualToString:@"inputTwoView"]) {
GCTwoViewController *twoView = segue.destinationViewController;
twoView.delegate =
self;
}
}
- (void)changeValue:(NSString *)value
{
self.label.text = value;
}
原代码如下: