我将一个自定义UIView的XIB文件作为UITableView的header view加载到视图控制器中。
XIB文件的文件所有者是视图控制器。我在UIViewController中声明了视图控制器和UIView的接口。
ViewController.h
@class ZeroStateView;
@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, weak) IBOutlet CustomUITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (weak, nonatomic) IBOutlet ZeroStateView *zeroStateView;
@end
@interface ZeroStateView : UIView
@property (weak, nonatomic) IBOutlet AutoLayoutLabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *titleIcon;
- (void)updateView;
@end
ViewController.m
- (void)prepareHeaderViewForZeroState{
ZeroStateView *sizingView = [ZeroStateView new];
[[[NSBundle mainBundle] loadNibNamed:@"ZeroStateView" owner:self options:nil] objectAtIndex:0];
sizingView = self.zeroStateView;
[sizingView updateView];
self.tableView.tableHeaderView = sizingView;
UIView *headerView = self.tableView.tableHeaderView;
CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
CGRect headerFrame = headerView.frame;
headerFrame.size.height = height;
headerView.frame = headerFrame;
self.tableView.tableHeaderView = headerView;
}
@end
@implementation ZeroStateView
-(void)updateView{
self.titleIcon.alpha = 0.5;
UIFontDescriptor *titleFontDescriptor = [UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleSubheadline];
self.titleLabel.text = @"This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. This is a long text message and its really long. ";
}
AutolayoutLabel类覆盖了以下方法:
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
// For multiline label, preferredMaxLayoutWidth always matches the frame width
if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) {
self.preferredMaxLayoutWidth = self.bounds.size.width;
[self setNeedsUpdateConstraints];
}
}
systemLayoutSizeFittingSize:UILayoutFittingCompressedSize计算出的高度为0。因此,我得到以下视图作为表头视图:
当我添加实际高度时,uilabel会溢出。我希望uiview随着标签高度的增加而增长。
headerFrame.size.height = self.sizingView.frame.size.height;
下面是该UIView约束的截屏:
我错过了什么?有人能指出来吗?
更新 我创建了一个项目供大家检查问题所在。
ZeroStateView *sizingView = [ZeroStateView new];
。 - pteofilprepareHeaderViewForZeroState
函数? - pteofil