iOS -- delegate

本文介绍如何在Objective-C中利用委托模式控制视图变化。通过定义代理协议、声明方法及属性,实现触摸开始时改变视图颜色和位置的功能。演示了从协议声明到方法实现的完整过程。
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];
}

ViewController.m
- (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






















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值