今天,总结一下iOS开发中常用到的委托(delegate)的应用。
效果图:
首页此时label的text为空
点击button进入第二页,通过点击第二页的button返回第一页,同时也为第一页的label的text传值
此时首页的效果
关键代码如下:
首先新建一个协议:
#import <Foundation/Foundation.h>
@protocol delegate <NSObject>
@optional
- (void)setTitle:(NSString *)string;
@end
FirstViewController的关键代码:
首先,FirstViewController.h里面申明继承次协议
#import <UIKit/UIKit.h>
#import "delegate.h"
@interface FirstViewController : UIViewController<delegate>
@property (retain,nonatomic) UILabel *label_1;
@end
FirstViewController.m里面的关键方法:
- (void)setTitle:(NSString *)string
{
[label_1 setText:string];
}
- (void)StepSecond
{
SecondViewController *secondViewController = [[SecondViewController alloc]init];
[self presentViewController:secondViewController animated:YES completion:nil];
secondViewController.setValuce = self;
}
SecondViewController.h里的关键代码:
#import <UIKit/UIKit.h>
#import "delegate.h"
@interface SecondViewController : UIViewController
@property (retain,nonatomic) id<delegate>setValuce ;
@end
SecondViewController.m的关键代码
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
UILabel *label_2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 200, 50)];
label_2.center = CGPointMake(160, 200);
[label_2 setText:@"Second Page"];
label_2.backgroundColor = [UIColor grayColor];
[self.view addSubview:label_2];
UIButton *button_2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button_2.frame =CGRectMake(0, 0, 50, 40);
button_2.center = CGPointMake(160, 380);
[button_2 addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button_2];
}
- (void)back
{
[self.setValuce setTitle:@"FirstPage1"];
[self dismissViewControllerAnimated:YES completion:nil];
}
总结过程:
要利用delegate进行传值,具体工程如下:
首先,需要新建一个protocol,在里面申明协议名和需要遵守的方法
其次,在需要代理对象里面执行三个关键步骤:
1 声明继承前面新建的协议
2 具体实现协议声明的方法
3 代理名.delegate = self(及理解为申明需要找代理的类的代理对象为此)
最后在需要找代理的类里面进行相应方法的调用
demo下载地址:http://download.csdn.net/detail/zhuangjingweijojo/5215381