UITableView&部分 - 检测部分标题是否保持在顶部

时间:2014-04-04 17:38:18

标签: objective-c uitableview

我需要这个,因为我需要更改一个部分的背景颜色。例如,如果顶部的部分则为蓝绿色。

我尝试了很多东西,但最后我的想法也是如此。

4 个答案:

答案 0 :(得分:2)

试试这个

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.backgroundColor = section == 0 ? [UIColor blueColor] : [UIColor greenColor];

    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    // header.contentView.backgroundColor = [UIColor blackColor];
}

考虑顶部意味着第一部分。

修改

如果您想根据滚动更改颜色并确定哪个部分位于顶部而哪些部分不在,那么您必须实现UIScrollViewDelegate,以便您可以处理滚动委托。你可以试试这样的东西

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSIndexPath *firstVisibleIndexPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0];
    NSLog(@"first visible cell's section: %i, row: %i", firstVisibleIndexPath.section, firstVisibleIndexPath.row);
}

参考文献:UIScrollViewDelegate implementationDetecting top cell in TableView

答案 1 :(得分:1)

试试这个:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    NSArray* visibleCellIndexPaths = [tableView indexPathsForVisibleRows];

    //Set all header views to have a blue background color.
    [view setBackgroundColor:[UIColor blueColor]];

    if(visibleCellIndexPaths.count > 0)
    {
        //Set the topmost visible section header view to have green background color.
        [[tableView headerViewForSection:[visibleCellIndexPaths[0] section]] setBackgroundColor:[UIColor greenColor]];
    }
}

答案 2 :(得分:0)

只需检查要查找的节标题的框架是否已移到顶部。

答案 3 :(得分:0)

@faisal Ali答案的快速版本

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    view.backgroundColor = section == 0 ? UIColor.white : UIColor.clear
}