ObjC中委托(delegate)用法

委托的用法,在本文中,将以UITableView列表内,自定义cell的button点击事件委托(delegate)UITableViewController执行任务,如刷新界面、处理数据等为例,进行演示。

1.创建一个 delegate

新建RZDoSomethingDelegate.h文件中:
objc

import <Foundation/Foundation.h>

@protocol RZDoSomethingDelegate <NSObject>

@option

  • (void)doSomething:(id)param;

@end
objc

2.委托者声明一个delegate

委托者自定义cell头文件(RZCustomCell.h)中,使用弱引用声明delegate属性
objc

import "RZDoSomethingDelegate.h"

@interface RZCustomCell : UITableViewCell

pragma mark - 委托

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

@end
objc

3.委托者调用delegate内的方法(method)

RZCustomCell.m中,按钮被点击时,使用委托执行任务,传递上下文参数
objc
@implementation RZCustomCell

  • (void)initSubview
    {
    //button初始化
    UIButton *button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(onClick) forControlEvents:UIControlEventTouchUpInside];
    }

  • (void)onClick
    {
    [self.delegate doSomething:self.detail];
    }

@end
objc

4.被委托者设置delegate,以便委托者调用

在RZUITableViewController.m文件中,设置被委托者
objc
@interface RZUITableViewController () <ZCGiftExchangeDelegate>
@end

@implementation RZUITableViewController

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    RZCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    //设置被委托者为viewController自己
    cell.delegate = self;

    if (!cell) {
    cell = [[RZCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@“identifier”];

    }

    return cell;
    }

@end
objc

5.被委托者实现Delegate 所定义的方法

在RZUITableViewController.m文件中,实现被委托方法
objc
@interface RZUITableViewController () <ZCGiftExchangeDelegate>
@end

@implementation RZUITableViewController

  • (void)doSomething:(id)param
    {
    //接受委托者的参数,进行数据处理、页面刷新等操作
    }

@end
objc

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,386评论 30 472
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,768评论 19 139
  • 1.OC里用到集合类是什么? 基本类型为:NSArray,NSSet以及NSDictionary 可变类型为:NS...
    轻皱眉头浅忧思阅读 5,228评论 0 3
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,272评论 4 61
  • 她总是一个人待在那里。平常的时候看着她开开心心的和朋友一起,一旦一起坐下她就变的很是沉默。她是一个笨女孩,...
    沐沐123阅读 3,638评论 0 1