簡體   English   中英

ViewForHeaderInSection代碼僅適用於標頭出隊

[英]ViewForHeaderInSection code works only on header dequeueing

我有自定義的tableView標頭,但是我指定標頭文本顏色和分隔線的代碼僅在將標頭從屏幕上滾動出來時才可用。 只有這樣,它們才會以白色文本顏色和可見的分隔符返回。 我的代碼有什么問題,標題在第一次加載時就沒有以正確的狀態返回?

- (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];
    }
}

原因是在出隊之前,標題的幀等於CGRectZero 這意味着,將來會調整頭的大小,並且需要為分隔符設置適當的自動調整大小的掩碼。 然后,分隔符也將被調整大小。

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

[header.contentView addSubview:separatorLine];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM