如何动态设置UITableView节标题的背景颜色?

时间:2014-05-04 04:55:37

标签: ios objective-c uitableview

我正在努力实现类似于iPhone上的照片应用的UITableView部分标题。顶部标题视图应具有灰色背景,其他标题视图应具有白色背景。基于此,我有几个问题需要帮助:

  1. 如何找出顶部的哪个部分标题(例如,与导航栏相邻)?请注意,导航栏是半透明的(意味着它会在自身下方显示单元格),因此我无法找到可见的单元格,然后根据该单元检索部分。

  2. 将顶部标题的背景颜色更改为不同的颜色然后在不再是顶部颜色时更改为原始颜色的方法应该是什么?

1 个答案:

答案 0 :(得分:0)

制作属性NSUInteger sectionPath并使用0中的viewDidLoad对其进行初始化。

创建headerView,并为特定部分更改该视图的backgroundColor。

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
     UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 30)];

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, headerView.frame.size.width, headerView.frame.size.height)];

    headerLabel.textAlignment = NSTextAlignmentCenter;
    headerLabel.text = [titleArray objectAtIndex:section];

    if(section == sectionPath) {
        headerLabel.backgroundColor = [UIColor grayColor];
    }
    else {
        headerLabel.backgroundColor = [UIColor whiteColor];
    }

    [headerView addSubview:headerLabel];    

    return headerView;
}

在滚动期间动态查找UITableView中最顶部的标题

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    for (NSIndexPath* i in [yourTableViewName indexPathsForVisibleRows]) {
      sectionPath = [i indexAtPosition:0];
    }
}
相关问题