zoukankan      html  css  js  c++  java
  • iOS代理模式(delegate)的使用

    前言:

    代理模式是iOS中非常重要的一个模式,iOS SDK中的系统控件几乎都用到了代理模式。代理模式用来处理事件监听、参数传递功能。

    协议创建(Protocol):

    可手打如下代码,或者在代码块里面搜索"protocol",然后把协议的代码拖拽出来

    @protocol FullcellDalegate <NSObject>

     

    @required//遵守协议必须实现的方法

    -(void)fullcellSelect:(NSIndexPath *)index WithBtnType:(NSInteger)type;

     

    @optional //遵守协议 实现不实现方法都可以

     

     

    @end

     

    在协议当中,方法的声明,被@required修饰,那么就准守这个协议的类,必须实现这个方法,否则就会发出警告。

    被@optional修饰,那么准守这个协议的类,可以实现这个方法,也可以不实现这个方法,不实现编译器也不会报警告。

    初始化:

    @property (nonatomic, weak) id<FullcellDalegate>delegate;

     

    代理的初始化要用”weak“修饰,否则会警告

     

     

    代理事件的监听:

     

    if ([self.delegate respondsToSelector:@selector(fullcellSelect:WithBtnType:)]) {

            [self.delegate fullcellSelect:self.indexpath WithBtnType:btn.tag];

        }

     

    方法使用的时候要先判断方法是否实现,然后才能使用。若方法没有实现就使用该方法,会崩溃。

     

     

    遵守协议:

     

    @interface MainVideoController ()<UITableViewDelegate, UITableViewDataSource, ZFPlayerDelegate, FullcellDalegate>

    cell.delegate = self;

     

    方法实现:

     

    -(void)fullcellSelect:(NSIndexPath *)index WithBtnType:(NSInteger)type

    {

     

    }

     

     

     

     

     

  • 相关阅读:
    for循环中变量的作用域问题
    一个数与0进行按位或,能取整
    Spring中日志的使用(log4j)
    MyBatis实现动态语句操作
    MyBatis实现简单增删改查操作
    python计算2的平方根,并输出小数点后的第100万位数字
    Spring配置文件报错:Multiple annotations found at this line: - Element type "beans" must be followed by either attribute specifications, ">" or "/>". - Start tag of element <beans>
    python跳出多重循环
    python中的生成器(二)
    python中的生成器(一)
  • 原文地址:https://www.cnblogs.com/yxl-151217/p/10411074.html
Copyright © 2011-2022 走看看