• IOS代理(初级)


    协议的作用以及协议的用法

    1.协议一般用作两个类之间的通信

    2.协议声明了一组所有类对象都可以实现的借口

    3.协议用@prltocol关键字声明 它本身不是类

    4.参与协议的两个对象,代理者和委托者

    5.代理,实现协议的某个方法,实现这个协议

    6.委托,用自己的方法指定要实现协议方法的对象(代理),代理来实现对应的方法

    7.@required---必须实现的方法  @optional---可以选择的方法  默认@required

    例子:

    这是一个简单的代理回调,包含传参

    // 非正式协议

    @protocol BCViewDelegate <NSObject>

    // 参数
    - (void)BCViewButtonDidClicked:(NSString *)text;

    @end

    委托类

    @interface BCView : UIView
    // 写属性代理                                                    
    @property(nonatomic,retain)id<BCViewDelegate>delegate;

    @end

    @implementation BCView

    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self) {
            // Initialization code
            [self addAllViews];
            
        }
        return self;
    }

    - (void)addAllViews
    {

        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(100, 100, 100, 40);
        // 绑定点击事件
        [button addTarget:self action:@selector(buttonDidClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [button setTitle:@"测试" forState:UIControlStateNormal];
        
        [self addSubview:button];
        
    }

    - (void)buttonDidClicked:(UIButton *)send
    {

        [self.delegate BCViewButtonDidClicked:@"杨过"];
        
    }

    @end
    代理类:
    @interface BCViewController ()<BCViewDelegate>
    @property(nonatomic,retain)BCView *rootView;
    @end

    @implementation BCViewController
    - (void)dealloc
    {
        [_rootView release];
        [super dealloc];
    }

    - (void)loadView
    {

        self.rootView = [[BCView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        self.view = self.rootView;
        [_rootView release];
    }

    - (void)viewDidLoad
    {
        [super viewDidLoad];
       
        self.rootView.delegate = self;
        
    }

    - (void)BCViewButtonDidClicked:(NSString *)text
    {
        NSLog(@"%@",text);

        NSLog(@"代理实现button点击");
    }
    - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
        if ([self isViewLoaded] && self.view.window == nil) {
            self.view = nil;
        }
    }

    @end

    两个类之间传值,可以用代理也可以不用代理(不实用),复杂的项目中,比如第三个类要得到协议方法的返回值,用代理会比较方便。

    可以把代理对象设置为自身,可以在自身中实现协议的方法

  • 相关阅读:
    dropdownlist下拉框加--请选择---
    vs2012中自带IIS如何让其他电脑访问
    win7 web开发遇到的问题-由于权限不足而无法读取配置文件,无法访问请求的页面
    无法打开登录所请求的数据库 "xxxx"。登录失败。 用户 'NT AUTHORITYSYSTEM' 登录失败。
    如何实现删除确认
    如何获取GridView的总记录数?
    SQL两张表如何关联
    ES7学习笔记——Array.prototype.includes和求幂运算符**
    一些常用的JavaScript正则表达式
    Vue.js 2.x中事件总线(EvevntBus)及element-ui中全屏loading的使用
  • 原文地址:https://www.cnblogs.com/bachl/p/4619571.html
Copyright © 2020-2023  润新知