1、协议是一组通讯协议,一般用作两个类之间的通信。
2、协议声明了一组所有类对象都可以实现的接口。
3、协议不是类,用@protocol关键字声明一个协议,其中,有两个预编译指令,@optional:表示可以选择实现的方法,@required:表示必须实现的方法。
4、与协议有关的两个对象,代理者和委托者,委托者委托代理者实现某些方法。
5、代理,实现协议的方法。
6、委托者,用自己的方法使另一个对象(代理者)替自己执行一些操作。
@protocol changeColor <NSObject>
@required
- (void)changeBlue;
@optional
- (void)changeYellow;
@end
#import <UIKit/UIKit.h>
@interface CostomView : UIView
@property (nonatomic,assign) id<changeColor>delegate;
@end
#import "CostomView.h"
@implementation CostomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.backgroundColor = [UIColor blueColor];
[btn setTitle:@"把viewcontroller变蓝色" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(blueClick:) forControlEvents:UIControlEventTouchUpInside];
btn.frame = CGRectMake(0, 0, 200, 100);
[self addSubview:btn];
UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn2.backgroundColor = [UIColor yellowColor];
[btn2 setTitle:@"把viewcontroller变黄色" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(yellowClick:) forControlEvents:UIControlEventTouchUpInside];
btn2.frame = CGRectMake(0, 100, 200, 100);
[self addSubview:btn2];
}
return self;
}
- (void)blueClick:(UIButton *)sender {
if ([self.delegate respondsToSelector:@selector(changeBlue)]) {
[self.delegate changeBlue];
}
}
- (void)yellowClick:(UIButton *)sender {
if ([self.delegate respondsToSelector:@selector(changeYellow)]) {
[self.delegate changeYellow];
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
}
*/
@end
#import <UIKit/UIKit.h>
#import "CostomView.h"
@interface ViewController : UIViewController <changeColor>
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
CostomView *view1 = [[CostomView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
view1.delegate = self;
[self.view addSubview:view1];
}
- (void)changeBlue {
self.view.backgroundColor = [UIColor blueColor];
}
- (void)changeYellow {
self.view.backgroundColor = [UIColor yellowColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
DEMO下载地址:http://download.csdn.net/detail/u011918080/6965353