如何调整superview的大小以适应autolayout的所有子视图?

DAK*_*DAK 141 uitableview ios autolayout

我对自动布局的理解是,它采用超视图的大小,并以约束和内在大小为基础计算子视图的位置.

有没有办法扭转这个过程?我想在约束和内在大小的基础上调整superview的大小.实现这一目标的最简单方法是什么?

我有在Xcode中设计的视图,我用它作为标题UITableView.该视图包括标签和按钮.标签的大小因数据而异.根据约束条件,标签成功按下按钮,或者如果按钮和superview底部之间存在约束,则标签将被压缩.

我找到了一些类似的问题,但他们没有很好的答案.

Tom*_*ift 149

正确使用的API是UIView systemLayoutSizeFittingSize:,传递UILayoutFittingCompressedSize或者UILayoutFittingExpandedSize.

对于正常UIView使用自动布局,只要您的约束正确,这应该可以正常工作.如果你想在一个UITableViewCell(例如确定行高)上使用它,那么你应该针对你的单元contentView格调用它并抓住高度.

如果您的视图中有一个或多个UILabel是多行的,则存在进一步的考虑因素.对于这些来说,preferredMaxLayoutWidth正确设置属性是非常重要的,这样标签提供了正确的intrinsicContentSize,将用于systemLayoutSizeFittingSize's计算.

编辑:根据请求,添加表格视图单元格的高度计算示例

使用autolayout进行表格单元格高度计算并不是非常有效,但它确实很方便,特别是如果您的单元格具有复杂的布局.

如上所述,如果您使用多行,UILabel则必须同步preferredMaxLayoutWidth到标签宽度.我使用自定义UILabel子类来执行此操作:

@implementation TSLabel

- (void) layoutSubviews
{
    [super layoutSubviews];

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

- (CGSize) intrinsicContentSize
{
    CGSize s = [super intrinsicContentSize];

    if ( self.numberOfLines == 0 )
    {
        // found out that sometimes intrinsicContentSize is 1pt too short!
        s.height += 1;
    }

    return s;
}

@end
Run Code Online (Sandbox Code Playgroud)

这是一个人为的UITableViewController子类,演示了heightForRowAtIndexPath:

#import "TSTableViewController.h"
#import "TSTableViewCell.h"

@implementation TSTableViewController

- (NSString*) cellText
{
    return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}

#pragma mark - Table view data source

- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
    return 1;
}

- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
    return 1;
}

- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
    static TSTableViewCell *sizingCell;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

        sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
    });

    // configure the cell
    sizingCell.text = self.cellText;

    // force layout
    [sizingCell setNeedsLayout];
    [sizingCell layoutIfNeeded];

    // get the fitting size
    CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
    NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));

    return s.height;
}

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
    TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];

    cell.text = self.cellText;

    return cell;
}

@end
Run Code Online (Sandbox Code Playgroud)

简单的自定义单元格:

#import "TSTableViewCell.h"
#import "TSLabel.h"

@implementation TSTableViewCell
{
    IBOutlet TSLabel* _label;
}

- (void) setText: (NSString *) text
{
    _label.text = text;
}

@end
Run Code Online (Sandbox Code Playgroud)

而且,这是故事板中定义的约束的图片.请注意,标签上没有高度/宽度限制 - 这些是从标签中推断出来的intrinsicContentSize:

在此输入图像描述

  • 在我从单元格底部到单元格中最低子视图底部添加最终垂直约束之前,这对我不起作用.似乎垂直约束必须包括单元格与其内容之间的顶部和底部垂直间距,以便成功进行单元格高度计算. (7认同)

Joh*_*rck 29

Eric Baker的评论让我想到了一个核心思想,即为了使视图的大小由其中的内容决定,然后放在其中的内容必须与包含视图有明确的关系才能驱动其高度(或宽度)动态."添加子视图"不会像您假设的那样创建此关系.您必须选择哪个子视图将驱动容器的高度和/或宽度...最常见的是放置在整个UI右下角的UI元素.这里有一些代码和内联注释来说明这一点.

请注意,这对于使用滚动视图的人来说可能特别有价值,因为围绕单个内容视图进行设计是很常见的,该视图根据您放入的内容动态地确定其大小(并将其传递给滚动视图).祝你好运,希望这有助于那里的人.

//
//  ViewController.m
//  AutoLayoutDynamicVerticalContainerHeight
//

#import "ViewController.h"

@interface ViewController ()
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) UILabel *myLabel;
@property (strong, nonatomic) UILabel *myOtherLabel;
@end

@implementation ViewController

- (void)viewDidLoad
{
    // INVOKE SUPER
    [super viewDidLoad];

    // INIT ALL REQUIRED UI ELEMENTS
    self.contentView = [[UIView alloc] init];
    self.myLabel = [[UILabel alloc] init];
    self.myOtherLabel = [[UILabel alloc] init];
    NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(_contentView, _myLabel, _myOtherLabel);

    // TURN AUTO LAYOUT ON FOR EACH ONE OF THEM
    self.contentView.translatesAutoresizingMaskIntoConstraints = NO;
    self.myLabel.translatesAutoresizingMaskIntoConstraints = NO;
    self.myOtherLabel.translatesAutoresizingMaskIntoConstraints = NO;

    // ESTABLISH VIEW HIERARCHY
    [self.view addSubview:self.contentView]; // View adds content view
    [self.contentView addSubview:self.myLabel]; // Content view adds my label (and all other UI... what's added here drives the container height (and width))
    [self.contentView addSubview:self.myOtherLabel];

    // LAYOUT

    // Layout CONTENT VIEW (Pinned to left, top. Note, it expects to get its vertical height (and horizontal width) dynamically based on whatever is placed within).
    // Note, if you don't want horizontal width to be driven by content, just pin left AND right to superview.
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to left, no horizontal width yet
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_contentView]" options:0 metrics:0 views:viewsDictionary]]; // Only pinned to top, no vertical height yet

    /* WHATEVER WE ADD NEXT NEEDS TO EXPLICITLY "PUSH OUT ON" THE CONTAINING CONTENT VIEW SO THAT OUR CONTENT DYNAMICALLY DETERMINES THE SIZE OF THE CONTAINING VIEW */
    // ^To me this is what's weird... but okay once you understand...

    // Layout MY LABEL (Anchor to upper left with default margin, width and height are dynamic based on text, font, etc (i.e. UILabel has an intrinsicContentSize))
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_myLabel]" options:0 metrics:0 views:viewsDictionary]];

    // Layout MY OTHER LABEL (Anchored by vertical space to the sibling label that comes before it)
    // Note, this is the view that we are choosing to use to drive the height (and width) of our container...

    // The LAST "|" character is KEY, it's what drives the WIDTH of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // Again, the LAST "|" character is KEY, it's what drives the HEIGHT of contentView (red color)
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[_myLabel]-[_myOtherLabel]-|" options:0 metrics:0 views:viewsDictionary]];

    // COLOR VIEWS
    self.view.backgroundColor = [UIColor purpleColor];
    self.contentView.backgroundColor = [UIColor redColor];
    self.myLabel.backgroundColor = [UIColor orangeColor];
    self.myOtherLabel.backgroundColor = [UIColor greenColor];

    // CONFIGURE VIEWS

    // Configure MY LABEL
    self.myLabel.text = @"HELLO WORLD\nLine 2\nLine 3, yo";
    self.myLabel.numberOfLines = 0; // Let it flow

    // Configure MY OTHER LABEL
    self.myOtherLabel.text = @"My OTHER label... This\nis the UI element I'm\narbitrarily choosing\nto drive the width and height\nof the container (the red view)";
    self.myOtherLabel.numberOfLines = 0;
    self.myOtherLabel.font = [UIFont systemFontOfSize:21];
}

@end
Run Code Online (Sandbox Code Playgroud)

如何使用autolayout.png调整superview的大小以适应所有子视图

  • 这是一个很好的技巧,并不为人所知.重复:如果内部视图具有固有高度并固定在顶部和底部,则外部视图不需要指定其高度,实际上将拥抱其内容.您可能需要调整内容压缩和内部视图的拥抱以获得所需的结果. (3认同)
  • 选择一种视图来驱动宽度正是我不能做的。有时一个子视图更宽,有时另一个子视图更宽。对这种情况有什么想法吗? (2认同)