delegate使用场景
控制一系列时间点,控制器可以实现这个代理方法,以便在适当地时机做适当的事
DelegateView.h
#warning 第一步:声明代理
@protocol DelegateViewDelegate <NSObject>
#warning 第二部: 声明代理方法
- (void)changeColor:(UIView *)view;
- (void)changeLocation:(UIView *)view;
@end
@interface DelegateView : UIView
#warning 第三部: 声明代理属性
@property (nonatomic, assign) id<DelegateViewDelegate> delegate;
DelegateView.m
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor colorWithRed:0.991 green:0.534 blue:0.682 alpha:1.000];
}return self;
}
#warning 第四步: 制定代理方法执行时刻
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.delegate changeColor:self];
[self.delegate changeLocation:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
DelegateView *delegateV = [[DelegateView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
#warning 第五步: 指定代理人
delegateV.delegate = self;
[self.view addSubview:delegateV];
}
#warning 第六步: 实现代理方法
- (void)changeLocation:(UIView *)view
{
if (view.frame.origin.y > self.view.frame.size.height - 100) {
view.frame = CGRectMake(100, 100, 100, 100);
}else
{
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y + 10, view.frame.size.width, view.frame.size.height);
}
}
- (void)changeColor:(UIView *)view
{
view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 256.0 green:arc4random() % 256 / 256.0 blue:arc4random() % 256 / 256.0 alpha:1];
}
Demo地址:https://github.com/Lyuci/LYC_UseDelegate