您的位置:首页 > 移动开发 > IOS开发

IOS-协议

2014-04-14 10:22 330 查看
----------------------------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
----------------------------MainViewController.h声明

#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

----------------------------MainViewController.h

#import <UIKit/UIKit.h>
//添加协议
#import "ProtocolFirst.h"
@interface BossView : UIView
//添加
@property(nonatomic,retain) id<ProtocolFirst> delegate;
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: