UI 04 代理设计模式

delegate 也是用来解耦的, 他不再是简简单单让目标去执行一个动作了,而是让delegate去处理一些事件.
这跟在OC中学习的协议是一样的, 分为6步.
还是创建一个继承于UIView 的 MyButton类.
MyButton.h代码如下:

#import <UIKit/UIKit.h>
// 1.声明一份协议
@protocol MyButtonDelegate <NSObject>
// 协议内容,即代理人需要做的事情:改颜色.
- (void)changeColor;
@end

@interface Mybutton : UIView
//2.设置代理人属性
@property (nonatomic,assign)id<MyButtonDelegate>delegate;
@end

MyButton.m代码如下:

#import "Mybutton.h"

@implementation Mybutton

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //3.设置代理人执行的方法.
    [self.delegate changeColor];
}

@end

根视图.m文件中代码:

#import "MainViewController.h"
#import "Mybutton.h"
// 4. 引头文件,签协议
@interface MainViewController ()<MyButtonDelegate>


@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    Mybutton *mybutton = [[Mybutton alloc] initWithFrame:CGRectMake(270, 450, 50, 50)];
    mybutton.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:mybutton];
    [mybutton release];
    //5.设置代理人
    mybutton.delegate = self;
}

    // 6.实现协议中的方法.
- (void)changeColor{
    self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:0.8];
}

效果如下图显示:
每点击一次黄色的MyButton后,颜色就会改变
这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章