----------------------------MainViewController.m
#import "MainViewController.h"
//导入类
#import "BossView.h"
@interface MainViewController ()
@end
@implementation MainViewController
//每个类都必须写dealloc(在mrc模式xia)
-(void)dealloc{
[super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
BossView * boss = [[BossView alloc] initWithFrame:CGRectMake(100, 100, 100,100)];
[boss setBackgroundColor:[UIColor blackColor]];
// 调用协议实现的方法
boss.delegate = self;
[self.view addSubview:boss];
[boss release];
}
//协议中的方法
- (void)doSomeThing{
NSLog(@"%s",__func__);
}
@end
#import <UIKit/UIKit.h>
//记得导入协议
#import "ProtocolFirst.h"
//记得添加协议
@interface MainViewController : UIViewController<ProtocolFirst>
@end
----------------------------MainViewController.m
#import "BossView.h"
@implementation BossView
-(void)dealloc{
[super dealloc];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// 设置按钮
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50,50)];
[button setBackgroundColor:[UIColor redColor]];
[button addTarget:self action:@selector(buttonAction:)forControlEvents:UIControlEventTouchUpInside ];
[self addSubview:button];
[button release];
}
return self;
}
// 用属性传进来的类(符合定义的协议的)
-(void)buttonAction:(id)sender{
// 判断是否响应了协议中的方法
if ([self.delegate respondsToSelector:@selector(doSomeThing)]) {
// 调用协议中的方法
[self.delegate doSomeThing];
}
}
@end
#import <UIKit/UIKit.h>
//添加协议
#import "ProtocolFirst.h"
@interface BossView : UIView
//添加
@property(nonatomic,retain) id<ProtocolFirst> delegate;
@end