自定义代理的使用比较频繁,掌握之后可使编程更加灵活。
代理类DaiLi
DaiLi.h
#import <UIKit/UIKit.h> //自定义代理 @protocol DaiLiDelegate <NSObject> //代理方法 - (void)change; @end @interface DaiLi : UIView @property(nonatomic,strong)UIButton *btn; @property(nonatomic,strong)id <DaiLiDelegate>delegate; @end
DaiLi.m
#import "DaiLi.h" @implementation DaiLi @synthesize btn; - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 50)]; //初试按钮颜色为红色 btn.backgroundColor = [UIColor redColor]; [btn addTarget:self action:@selector(clicked) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:btn]; } return self; } - (void)clicked { //点击方法中将按钮颜色变为黑色 btn.backgroundColor = [UIColor blackColor]; //代理方法 [self.delegate change]; } @end
代理的实现类ViewController
ViewController.m
#import "ViewController.h" #import "DaiLi.h" @interface ViewController ()<DaiLiDelegate> { DaiLi *daiLi; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; daiLi = [[DaiLi alloc]initWithFrame:CGRectMake(20, 100, self.view.frame.size.width-40, 100)]; daiLi.delegate = self; [self.view addSubview:daiLi]; } //代理方法的实现 - (void)change { //此处讲按钮颜色变为黄色 daiLi.btn.backgroundColor = [UIColor yellowColor]; } @end
点击按钮我们会发现,结果并不是按钮点击方法中的将按钮变为黑色。这是因为在代理的实现方法里再次改变了按钮的颜色,使其变为黄色。
时间: 2024-10-11 06:58:08