iOS学习笔记(3)——响应自定义的UITableViewCell及其内部控件的点击事件

这几天自己动手写新浪微博,用到了自定义的tablecell。由于Cell内部诸多控件的都能响应用户的点击,使用UITableView的didSelectRowAtIndexPath:代理方法已经不能满足项目需求。使用代理模式实现。

1、在自定义的Cell中定义一个接口及方法

.h文件
#import <UIKit/UIKit.h>

@class StatusCellFrame;
@class StatusCell;

@protocol StatusCellDelegate <NSObject>
@optional
-(void)RepostStatusTap:(StatusCell *)cell;

@end

@interface StatusCell : UITableViewCell
{
    UIImageView *_background;
    UIImageView *_selectedBackground;
    
    UIImageView *_reposted; // 被转发微博的父控件
}

@property (strong, nonatomic)StatusCellFrame *cellFrame;

@property (assign, nonatomic)id<StatusCellDelegate> delegate;

@end

.m文件中响应控件点击事件方法

UITapGestureRecognizer *repostStatusTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(repostStatusTap)];
    
    // 1. 被转发微博的父控件
    _reposted = [[UIImageView alloc]init];
    _reposted.image = [UIImage resizedImage:@"timeline_retweet_background.png"];
    _reposted.userInteractionEnabled = YES;
    [_reposted addGestureRecognizer:repostStatusTap];
    [self.contentView addSubview:_reposted];

#pragma mark 被转发微博的点击事件
-(void)repostStatusTap
{
    if (_delegate && [_delegate respondsToSelector:@selector(RepostStatusTap:)]) {
        [_delegate RepostStatusTap:self];
    }
}


2、当内部控件接收到用户的点击事件后,由代理调用方法,触发相应事件

HomeTableViewController.m

#pragma mark 实现代理方法,响应被转发微博的点击事件
-(void)RepostStatusTap:(StatusCell *)cell
{
    StatusDetailController *detail = [[StatusDetailController alloc]init];
    NSLog(@"转发微博点击");
    [self.navigationController pushViewController:detail animated:YES];
}

当然,在创建cell的时候不要忘记为其设置代理

if (cell == nil) {
        cell = [[StatusCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.delegate = self;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值