如果我们点击UITableView中的Custom Section Header,然后将该部分移到顶部
我在UITableView
有一个Custom Section Header
,在那个部分头放置UIButton
在其正确的。我想要的是,如果我点击UIButton
,该特定的Section Header
应滚动到顶部。 而已
任何build议,一块代码将被赞赏。
第1步:设置节头的大小。 示例如下。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 55; }
第2步:创build并返回自定义的部分标题。
- (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步:创build和返回单元格(每行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]; }
你可以使用UITableView的scrollToRowAtIndexPath:atScrollPosition:animated:方法。 将button标签设置到该部分并调用他的动作:
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:button.tag] atScrollPosition:UITableViewScrollPositionTop animated:YES];