这几天自己动手写新浪微博,用到了自定义的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];
}
}
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;
}