ios:uitableview节标题锚到表顶部

Moh*_*gab 23 uitableview sectionheader ios

我正在尝试制作一个包含多个部分的表(如联系人应用程序)一切顺利,我在每个部分的顶部创建了自定义部分标题,显示代表此部分的字符.问题是我希望它像是联系人确切地说标题保持在顶部直到下一个标题崩溃...它怎么会发生这种情况

我正在使用以下代码(以便您更容易理解

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
   return [stateIndex count];
}



- (UIView *)tableView:(UITableView *)aTableView viewForHeaderInSection:(NSInteger)section
{

    UILabel *sectionHeader = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    sectionHeader.backgroundColor = [UIColor clearColor];
    sectionHeader.font = [UIFont boldSystemFontOfSize:18];
    sectionHeader.textColor = [UIColor whiteColor];
    sectionHeader.text = [stateIndex objectAtIndex:section];
    sectionHeader.textAlignment=UITextAlignmentCenter;
    return sectionHeader;
}
//---set the index for the table---
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return stateIndex;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //---get the letter in each section; e.g., A, B, C, etc.---
    NSString *alphabet = [stateIndex objectAtIndex:section];

    //---get all states beginning with the letter---
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
    NSArray *states = [resultPoets filteredArrayUsingPredicate:predicate];

    //---return the number of states beginning with the letter---
    return [states count];

}


- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"Cell";
    PoemsCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    int row = indexPath.row;




    //---get the letter in the current section---
    NSString *alphabet = [stateIndex objectAtIndex:[indexPath section]];

    //---get all states beginning with the letter---
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
    NSArray *states = [resultPoets filteredArrayUsingPredicate:predicate];

    if ([states count]>0) {
        //---extract the relevant state from the states object---
        NSString *cellValue = [states objectAtIndex:row];

        cell.poemText.text = cellValue;

    }



    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 43

如果您使用表视图样式"Plain"而不是"Grouped",这应该会自动运行.

从文档:

UITableViewStylePlain:普通表视图.任何节页眉或页脚都显示为内联分隔符,并在滚动表视图时浮动.

UITableViewStyleGrouped:一个表视图,其部分显示不同的行组.节标题和页脚不会浮动.

  • 别忘了使用 - (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section; 如果你想为每个标题增加不同的高度. (5认同)
  • 哦,我的这就像一个完美的答案和完美的评论...祝福你们俩 (2认同)
  • 即使我滚动到不同的部分,是否可以修改'Plain'以显示标题部分?我希望将标题聚合到顶部,因为我可以折叠/展开它们.如果表非常大,这只是帮助在它们之间导航. (2认同)