我对自动布局的理解是它基于约束和内在大小,计算子视图的位置,并考虑父视图的大小。
是否有一种方法可以反向实现这个过程?我想根据约束和内在大小来调整父视图的大小。最简单的实现方式是什么?
我在Xcode中设计了一个视图,用作UITableView
的标题。这个视图包含一个标签和一个按钮。标签的大小取决于数据。根据约束,标签成功地将按钮向下推动,或者如果存在按钮与父视图底部之间的约束,则标签被压缩。
我找到了一些类似的问题,但它们没有好的且易于操作的答案。
我对自动布局的理解是它基于约束和内在大小,计算子视图的位置,并考虑父视图的大小。
是否有一种方法可以反向实现这个过程?我想根据约束和内在大小来调整父视图的大小。最简单的实现方式是什么?
我在Xcode中设计了一个视图,用作UITableView
的标题。这个视图包含一个标签和一个按钮。标签的大小取决于数据。根据约束,标签成功地将按钮向下推动,或者如果存在按钮与父视图底部之间的约束,则标签被压缩。
我找到了一些类似的问题,但它们没有好的且易于操作的答案。
正确的API是UIView systemLayoutSizeFittingSize:
,传递UILayoutFittingCompressedSize
或UILayoutFittingExpandedSize
参数。
对于使用autolayout的普通UIView
,只要您的约束条件正确,这应该可以正常工作。如果您想在UITableViewCell
上使用它(例如确定行高),则应针对单元格的contentView
调用它并获取高度。
如果您的视图中有一个或多个多行UILabel
,则需要考虑更多因素。对于这些,必须正确设置preferredMaxLayoutWidth
属性,以便标签提供正确的intrinsicContentSize
,该尺寸将用于systemLayoutSizeFittingSize
的计算。
编辑:根据请求,添加一个表格视图单元格高度计算的示例
对于表格单元格高度计算来说,使用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
这是一个编造的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
一个简单的自定义单元格:
#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
这是Storyboard中定义的约束条件的图片。请注意,标签上没有高度/宽度的约束-这些约束从标签的intrinsicContentSize
推断出来:
sizingCell
或其contentView
都有非零大小了。 - MkValsizingCell
的宽度与您的tableView
的宽度匹配。 - MkVal请注意,对于那些使用滚动视图工作的人来说,这可能特别有价值,因为通常会围绕一个单个内容视图设计,该视图根据放入其中的任何内容动态地确定其大小(并将此信息传达给滚动视图)。祝你好运,希望这能帮助到某个人。
//
// 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
@interface ViewController : UIViewController {
IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
将此约束出口连接到您的子视图约束或超级视图约束,并根据您的要求进行设置,如下所示。
self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign
这可以针对较大的UIView
中的普通subview
完成,但是对于headerViews
,它不会自动工作。 headerView
的高度由tableView:heightForHeaderInSection:
返回的内容确定,因此您必须根据UILabel
的height
以及所需的UIButton
和任何padding
来计算height
。 您需要执行以下操作:
-(CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section {
NSString *s = self.headeString[indexPath.section];
CGSize size = [s sizeWithFont:[UIFont systemFontOfSize:17]
constrainedToSize:CGSizeMake(281, CGFLOAT_MAX)
lineBreakMode:NSLineBreakByWordWrapping];
return size.height + 60;
}
在这里headerString
是你想填充UILabel
的任意字符串,而281是UILabel
的width
(如在Interface Builder
中设置)