ios - ViewForHeaderInSection 代码仅适用于 header 出列

标签 ios uitableview

我有自定义的 tableView header ,但是我指定 header 文本颜色和分隔线的代码仅在 header 出列时才有效,当我将它们滚动到屏幕外时。只有这样他们才会返回白色文本颜色和可见的分隔符。我的代码有什么问题,即 header 在第一次加载时没有以正确的状态返回?

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"FIRST HEADER";
    } else if (section == 1) {
        return @"SECOND HEADER";
    } else {
        return @"THIRD HEADER";
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{    
    UITableViewHeaderFooterView *myHeaderView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];

    if (!myHeaderView) {

        myHeaderView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"header"];
    }
    myHeaderView.textLabel.textColor = [UIColor whiteColor];

    CGFloat leftMargin = 0.0;
    CGFloat lineWidth = 1.0;

    UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, myHeaderView.frame.size.height - lineWidth, myHeaderView.frame.size.width - leftMargin, lineWidth)];
    separatorLine.backgroundColor = [UIColor whiteColor];

    [myHeaderView addSubview:separatorLine];

    return myHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20.0;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isMemberOfClass:[UITableViewHeaderFooterView class]]) {

        ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = [UIColor clearColor];
    }
}

最佳答案

原因是您的 header 帧在出队前等于 CGRectZero。这意味着,该 header 将来会调整大小,您需要为分隔符设置适当的自动调整掩码。然后,分隔符也将调整大小。

UIView *separatorLine = [[UIView alloc] initWithFrame:CGRectMake(leftMargin, 0, 0, lineWidth)];
separatorLine.backgroundColor = [UIColor redColor];
separatorLine.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;

[header.contentView addSubview:separatorLine];

关于ios - ViewForHeaderInSection 代码仅适用于 header 出列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21853323/

相关文章:

ios - 为什么当我滑动 View 时 UITableViewCell 改变了大小

ios - UITableViewCell 中的 UIStackView 在 AutoLayout 上无法正确调整

ios - URLConnection sendSynchronousRequest 问题?

ios - DidSelectRow 方法由于 tapGestureRecognizer 而被禁用

ios - 红色分隔线未出现在 UITableViewCell 中的自定义标题下

ios - 附件类型将 tableviewcell 推向左侧

ios - 在 while 循环中快速保存到 Parse

ios - 如何检测路线变化或将路线与带有反应导航的屏幕匹配

ios - 如何去除不透明度但保留 UIImage 的 alpha channel ?

ios - 使用arc4random ios的概率方程