如果我们点击UITableView中的Custom Section Header,那么将该部分移到顶部

Sha*_*shi 7 iphone uitableview ios

我有一个Custom Section Headerin UITableView,在那个部分标题上放在UIButton它的右边.我想要的是,如果我点击UIButton,那个特别Section Header应该滚动到顶部.而已

任何建议,一段代码都会受到赞赏.

Sag*_*ari 17

第1步:设置Section标头的大小.示例如下.

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 55;
}
Run Code Online (Sandbox Code Playgroud)

第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;
}
Run Code Online (Sandbox Code Playgroud)

第3步:返回部分数量.(例如10)

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 10;
}
Run Code Online (Sandbox Code Playgroud)

第4步:每个部分的行数.(例如,每个部分4行)

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}
Run Code Online (Sandbox Code Playgroud)

第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;
}
Run Code Online (Sandbox Code Playgroud)

步骤6:添加事件以处理节标题上的TouchDown.

- (void)sectionTapped:(UIButton*)btn {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:btn.tag-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}
Run Code Online (Sandbox Code Playgroud)