1

大家好,我有一个 TableHeaderView,一切都由 Autolayout 管理:

  • UIImageView顶部应始终为 2:1,因此我设置了纵横比和其他所需的约束。

  • 4UIButtons应该始终是水平的,并且应该具有相同的高度和宽度。所以我使用等宽和等高以及 1:1 的纵横比

  • 我有两个UILabels设置numberOfLines为 0。我还创建了我的子类UILabel,因为preferredMaxLayoutWidth,像这样:

    - (void) layoutSubviews
    {
    [super layoutSubviews];
    
    if ( self.numberOfLines == 0 )
    {
    if ( self.preferredMaxLayoutWidth != self.frame.size.width )
    {
        self.preferredMaxLayoutWidth = self.frame.size.width;
        [self setNeedsUpdateConstraints];
     }
     }
    }
    

这是我的代码:

- (void)initializeHeaderViewLabels
{
 //After the Response from my server arrived i set the tableHeaderView with the Textdata
self.tableView.tableHeaderView = nil;

if((self.contentDict[@"title"]) != [NSNull null])
{
    self.headerTitleLabel.text = (self.contentDict[@"title"]);
}

if((self.contentDict[@"shortDescription"]) != [NSNull null])
{
    self.headerDescriptionLabel.text = (self.contentDict[@"shortDescription"]);
}

[self.headerView setNeedsLayout];
[self.headerView layoutIfNeeded];

CGFloat height = [self.headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = height;
self.headerView.frame = headerFrame;

[self.tableView setTableHeaderView:self.headerView];

}

我从我的服务器获取我的图像和文本UILabels,所以我必须等到响应到达,然后我调用initializeHeaderViewLabels

**我的问题是 tableHeaderView 在运行时太大了,所以我的 UILabels 被拉伸并且有很多空白。也许我想念什么?

4

5 回答 5

6

为了使它工作,您需要一些魔法或从表头视图迁移。我已经在这里回答了一个类似的问题。诀窍是tableHeaderView在通过自动布局评估它的高度后神奇地重置。我为此创建了示例项目:TableHeaderView+Autolayout

于 2015-04-30T09:23:51.930 回答
1

尝试以下解决方案

- (void)sizeHeaderToFit
{
    UIView *header = self.tableView.tableHeaderView;

    [header setNeedsLayout];
    [header layoutIfNeeded];

    CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    CGRect frame = header.frame;

    frame.size.height = height;
    header.frame = frame;

    self.tableView.tableHeaderView = header;
}

资源:

使用自动布局、IB 和字体大小时表头视图高度错误

另请参阅下面的问题...!

如何使用自动布局设置 tableHeaderView (UITableView) 的高度?

于 2015-04-30T09:43:58.920 回答
0

我的问题是我在标题视图上设置了约束,这些约束将一些帧值映射到超级视图帧值。当我删除约束并直接设置框架时,一切正常。

于 2016-09-28T11:50:25.743 回答
-3

Header view height is set in the table view delegate. By default it is the same size as in interface builder which is too large when run in app since the width for interface builder is 600.

So what you need is to implement this method in UITableViewDelegate

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 200.0 // Set the desired height based on your device or what ever you are using.
}

And Objective-C version:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 200.0f;
}
于 2015-04-27T19:40:47.957 回答
-6
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{
    return 200;
}
于 2015-04-28T00:22:18.717 回答