首页 文章

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

提问于
浏览
1

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

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

  • 将顶部 Headers 的背景颜色更改为不同颜色,然后在不再是顶部颜色时返回原始颜色的方法应该是什么?

1 回答

  • 0

    使属性 NSUInteger sectionPath 并在 viewDidLoad 中使用 0 初始化它 .

    创建一个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 中的最顶部 Headers

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

相关问题