今天在幫朋友解決問題的時候碰見了一個問題音榜,點擊分組表格的表頭獲取當前的section。在協(xié)議方法中有點擊cell的方法赠叼,但沒有點擊表頭的協(xié)議方法嘴办。當時沒有思路,只想著怎么解決涧郊。所以用了比較愚蠢的辦法:在創(chuàng)建分組表格的時候妆艘,就把當前的section復(fù)制給button的tag值,當改變分組表格時批旺,會刷新表格汽煮,重新復(fù)制,這樣確實是解決了問題暇赤。不過通過詢問大神后翎卓,得到另外一種方法,分享給大家失暴。
-
首先讓大家看一下效果圖
Untitled.gif
這里演示的是自定義分組表格的表頭逗扒。我們只需要在創(chuàng)建表頭的協(xié)議方法中執(zhí)行這樣的代碼:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
TableViewHeader *view = [[TableViewHeader alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
view.name.text = [NSString stringWithFormat:@"第%@分區(qū)", @(section)];
view.section = section;//以屬性的方式把當前的section傳過去
view.didSelectHandler = ^(NSInteger section) {
//就可以在語句塊中寫你要執(zhí)行的方法了
NSLog(@"當前section為:%zd", section);
};
return view;
}
自定義表頭的代碼:
-
.h文件
@interface TableViewHeader : UIView
@property (nonatomic, strong) UILabel *name;
@property (nonatomic, assign) NSInteger section;
@property (nonatomic, copy) void (^didSelectHandler) (NSInteger section);
@end
-
.m文件
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame])
{
//設(shè)置表頭的背景顏色
self.backgroundColor = [UIColor groupTableViewBackgroundColor];
//給整個表頭添加手勢
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap)];
[self addGestureRecognizer:tap];
//布局
self.name = [[UILabel alloc] initWithFrame:CGRectMake(150, 10, 200, 20)];
self.name.font = [UIFont boldSystemFontOfSize:18];
[self addSubview:self.name];
}
return self;
}
#pragma mark - 點擊手勢方法
- (void)onTap
{//實現(xiàn)block語句塊
if (self.didSelectHandler)
{
self.didSelectHandler(_section);
}
}
其實還有蠻多方法的矩肩。