我在Custom Section Header
中有一个UITableView
,在那个标题标题上放置了UIButton
。我想要的是,如果我点击UIButton
,那个特定Section Header
应滚动到顶部。就是这样
任何建议,一段代码都会受到赞赏。
答案 0 :(得分:17)
第1步:设置Section标头的大小。示例如下。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 55;
}
第2步:创建&返回自定义的部分标题。
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UIView *aView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 55)];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(0, 0, 320, 55)];
[btn setTag:section+1];
[aView addSubview:btn];
[btn addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchDown];
return aView;
}
第3步:返回部分数量。 (例如10)
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
第4步:每个部分的行数。 (例如,每个部分有4行)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 4;
}
第5步:创建&返回单元格(每行的UITableViewCell)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text=[NSString stringWithFormat:@"%i_%i",indexPath.section,indexPath.row];
return cell;
}
第6步:添加事件以处理部分标题上的 TouchDown 。
- (void)sectionTapped:(UIButton*)btn {
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:btn.tag-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
答案 1 :(得分:2)
您可以使用UITableView中的scrollToRowAtIndexPath:atScrollPosition:animated:方法。 将按钮标记设置为该部分并调用其操作:
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:button.tag]
atScrollPosition:UITableViewScrollPositionTop animated:YES];