zoukankan      html  css  js  c++  java
  • 自定义代理

    自定义代理的使用比较频繁,掌握之后可使编程更加灵活。

    代理类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

    点击按钮我们会发现,结果并不是按钮点击方法中的将按钮变为黑色。这是因为在代理的实现方法里再次改变了按钮的颜色,使其变为黄色。

  • 相关阅读:
    JAVA爬虫实践(实践三:爬虫框架webMagic和csdnBlog爬虫)
    JAVA爬虫实践(实践一:知乎)
    JAVA爬虫实践(实践二:博客园)
    SpringMVC框架学习笔记(5)——数据处理
    SpringMVC框架学习笔记——各种异常、报错解决
    SpringMVC框架学习笔记(1)——HelloWorld
    angularjs springMVC 交互
    存储过程存放数据方式
    存储过程总结
    cssie7.0兼容
  • 原文地址:https://www.cnblogs.com/fanzhiying/p/5085132.html
Copyright © 2011-2022 走看看