我目前有一个UIView子类,作为UITableViewController的头视图。根据为特定项检索的数据,所有子视图的大小都有所不同。
在确定每个标签的大小之前,将调用UIView的layoutSubViews。这会导致一个问题,因为我在layoutSubViews方法中设置了视图的大小。因为它在我设置标签之前被调用,所以视图高度总是0。即使在设置了标签之后,我也调用setNeedsLayout,但是表视图的标题大小不会改变。
TableHeaderView *tableHeaderView = [[TableHeaderView alloc] initWithFrame:CGRectZero];
tableHeaderView.headerTitle.text = title;
tableHeaderView.headerOption1.text = headerOption1
tableHeaderView.headerOption2.text = headerOption2
tableHeaderView.headerOption3.text = headerOption3
[[self tableView] setTableHeaderView:tableHeaderView];
[tableHeaderView setNeedsLayout];
[tableHeaderView release];
这是我的UIView子类
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
UIView *headerView = self;
self.headerTitle = [[UILabel alloc] initWithFrame:CGRectZero];
self.headerTitle.numberOfLines = 3;
self.headerTitle.lineBreakMode = UILineBreakModeWordWrap;
[headerView addSubview:self.headerTitle];
[self.headerTitle release];
self.headerOption1 = [[UILabel alloc] initWithFrame:CGRectZero];
self.headerOption1.numberOfLines = 2;
self.headerOption1.lineBreakMode = UILineBreakModeWordWrap;
[headerView addSubview:self.headerOption1];
[self.headerOption1 release];
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
CGSize maxLabelSize;
/*...*/
[self.headerTitle setFrame:CGRectMake(10.0f, 10.0f, titleWidth, titleHeight)];
/*...*/
[self.headerOption1 setFrame:CGRectMake(10.0f, (self.headerTitle.frame.origin.y + self.headerTitle.bounds.size.height + 2.5f), pubWidth, pubHeight)];
/*...*/
[self setFrame:CGRectMake(0.0f, 0.0f, 320.0f, tableHeaderHeight)];
}
第二次调用layoutSubViews时,除了视图本身(tableHeaderHeight具有正确的高度),所有子视图的大小都正确。我不应该从这个方法调整视图的大小吗?有更好的办法吗?