iOS 代理协议传值
从ViewController跳转到FirstViewController, 在FirstViewController中传一个NSInteger值回来
ViewController.m
#import "ViewController.h"
#import "FirstViewController.h"
@interface ViewController () <PassValueDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor whiteColor];
_myButton = [UIButton buttonWithType:UIButtonTypeCustom];
_myButton.frame = CGRectMake(20, 20, 100, 100);
[_myButton setTitle:@"跳转" forState:UIControlStateNormal];
_myButton.backgroundColor = [UIColor redColor];
[_myButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_myButton];
}
// button点击事件 跳转到FirstViewController
- (void)clicked:(UIButton *)button
{
FirstViewController *firVC = [[FirstViewController alloc] init];
firVC.passDelegate = self;
[self presentViewController:firVC animated:YES completion:nil];
}
- (void)setValue:(NSInteger )value
{
NSLog(@"value ===== %ld", (long)value);
}
@end
FirstViewController.h
// 签协议 以及方法(名子自己起,类型为要传的值的类型)
@protocol PassValueDelegate <NSObject>
- (void)setValue:(NSInteger)value;
@end
@interface FirstViewController : UIViewController
// 签代理 属性
@property(nonatomic, assign) id<PassValueDelegate> passDelegate;
@property(nonatomic, assign)
NSInteger number;
@end
FirstViewController.m
@interface FirstViewController ()
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor greenColor];
_myButton = [UIButton buttonWithType:UIButtonTypeCustom];
_myButton.frame = CGRectMake(20, 20, 100, 100);
[_myButton addTarget:self action:@selector(clicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_myButton];
_number = 1000;
}
//代理遵从协议的方法
- (void)clicked:(UIButton *)button
{
[self.passDelegate setValue:_number];
[self dismissViewControllerAnimated:YES completion:nil];
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。