【发布时间】:2023-03-29 23:35:02
【问题描述】:
我正在加载自定义 UIView 的 XIB 文件作为视图控制器内 uitableview 的标题视图。
xib 文件的文件所有者是视图控制器。我在 uiviewcontroller 中声明了 viewcontroller 和 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;
这是 UIViews 约束的屏幕截图:
我在这里想念什么?谁能指出我?
更新 我创建了一个示例 project 供你们检查到底是什么问题。
【问题讨论】:
-
对于它的价值,在第一句话中陈述你的问题总是有帮助的。
-
如果您在 2 行后为其分配了其他内容,则不应调用此
ZeroStateView *sizingView = [ZeroStateView new];。 -
什么时候给
prepareHeaderViewForZeroState打电话? -
它在 viewwillappear 方法中调用
-
是的,期待视图的高度增加
标签: ios objective-c uitableview uiview autolayout