Objective-C 学习记录 - 30

1.代理的使用方法

定义协议:

/** 
 * 定义协议,将需要实现的方法列在其中
 * 协议名字最好为类名+Delegate,方法名最好以类名开头
 * 其中<NSObject>为基协议,遵守本协议时则同时获得基协议中的方法
 */
@protocol tableViewCellDelegate <NSObject>

- (void)tableViewCellDidClickPlusButton:(tableViewCell *)cell;
- (void)tableViewCellDidClickMinusButton:(tableViewCell *)cell;

@end

声明代理属性:

/** 声明代理属性,代理属性必须为weak类型,<>中为协议名 */
@property (weak, nonatomic) id <tableViewCellDelegate> delegate;

调用代理方法:

/** 
 * 调用可以先判断是否设置了代理对象(self.delegate)
 * 以及是否实现了代理方法([self.delegate respondsToSelector:@selector(方法名)])
 * 以避免不必要的错误,尤其是当协议方法为可选(optional)时
 */
if (self.delegate && [self.delegate respondsToSelector:@selector(tableViewCellDidClickPlusButton:)]) {
    [self.delegate tableViewCellDidClickPlusButton:self];
}

设置代理对象:

/** 声明遵守tableViewCellDelegate协议 */
@interface ViewController () <tableViewCellDelegate>


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"ID";
    FoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[FoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    /** 设置代理对象为self */
    cell.delegate = self;
    return cell;
}

实现代理方法:

/** 实现代理方法 */
- (void)tableViewCellDidClickPlusButton:(tableViewCell *)cell
{
    NSLog(@"%s", __func__);
}

- (void)tableViewCellDidClickMinusButton:(tableViewCell *)cell
{
    NSLog(@"%s", __func__);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值