IOS 代理模式初学讲解

学IOS大半年了,终于理顺了代理的思路。

看别人的讲解一直都没有理解好,和我自己的思维逻辑不符合。对于不理解有什么实际用处的东西总是学不好,现在终于理解了一些。

现在和大家分享一个小Demo。

问题:通过根视图控制器的子视图上的按钮点击来改变整个视图控制器的背景颜色。

点击前: 

点击后:

效果大家看到了,子视图上的按钮,如何改变根视图控制器的视图背景颜色的呢,这里就要用到代理。

把按钮按下的消息,发送给根视图控制器,来改变视图背景颜色。

代码如下:

gifView.h(继承UIView)中代码如下:

#import <UIKit/UIKit.h>

@protocol changColor <NSObject>

- (void)DoChangColor;

@end

@interface GifView : UIView
{
    id <changColor> delegate;
}

@property (nonatomic, retain) id <changColor> delegate;

@end



gifView.m中代码如下:

@implementation GifView
@synthesize delegate;

- (id)initWithFrame:(CGRect)frame
{
    
    self = [super initWithFrame:frame];
    if (self)
    {
        UIButton *button=[UIButton buttonWithType:UIButtonTypeSystem];
        button.backgroundColor=[UIColor redColor];
        button.frame=CGRectMake(50, 50, 200, 100);
        [button addTarget:self action:@selector(play) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
    }
    return self;
}

-(void)play
{
    [delegate DoChangColor];
}

@end

创建根视图RootViewController,代码如下:

RootViewController.m中代码如下:

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor orangeColor];
    GifView *tmp = [[GifView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    tmp.delegate = self;
    [self.view addSubview:tmp];
}

- (void)DoChangColor
{
    self.view.backgroundColor=[UIColor grayColor];
}

@end




希望通过这个Demo可以让初学者更好的理解代理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值