我对自动布局的理解是,它采用了超级视图的大小,并基于约束和内在大小来计算子视图的位置。
有没有办法扭转这个过程?我想基于约束和内在大小调整Superview的大小。最简单的方法是什么?
我在Xcode中设计了视图,并将其用作的标题UITableView
。该视图包括标签和按钮。标签的大小取决于数据。根据约束,标签可以成功按下按钮,或者如果按钮和超级视图底部之间存在约束,则标签将被压缩。
我发现了一些类似的问题,但没有好的和简单的答案。
正确使用的APIUIView systemLayoutSizeFittingSize:
是UILayoutFittingCompressedSize
或传递UILayoutFittingExpandedSize
。
对于正常UIView
使用自动布局的方法,只要您的约束正确,它就应该起作用。如果要在上使用它UITableViewCell
(例如确定行高),则应在单元格上调用它contentView
并抓住它的高度。
如果您的视图中有一个或多个多行UILabel,则需要进一步考虑。对于这些,preferredMaxLayoutWidth
必须正确设置属性,以使标签提供正确的intrinsicContentSize
,这将在systemLayoutSizeFittingSize's
计算中使用。
编辑:根据要求,为表格视图单元格添加高度计算的示例
使用自动布局进行表格单元格高度计算虽然效率不高,但它确实很方便,特别是如果您的单元格具有复杂的布局。
如上所述,如果您使用多行,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
而且,这是情节提要中定义的约束的图片。请注意,标签上没有高度/宽度限制-从标签的推断出这些限制intrinsicContentSize
:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句