IOS-协议

----------------------------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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值