我正在尝试在UITableview中创建一个包含3个标签的节标题,其布局看起来有点像这样
-------------------------------
| title | dist |
| |
| Description |
| |
-------------------------------
Title
和time
都是固定大小,但description
需要根据内容自动调整其高度,最小高度为单行文字。
我当前的标题结构由
组成UIView
|_ UIView
|_ UILabel
|_ UILabel
|_ UILabel
外部UIView是节标题本身,背景清晰,内部UIView是带标签的可见视图。
我所追求的是,节标题根据描述标签中的内容调整其高度。
我已尝试实施tableView:heightForHeaderInSection:
,但似乎没有效果。 iOS抱怨我必须打破限制,我认为这是有意义的,因为我设置了约束,但是然后用这种方法手动覆盖它们?
如何创建允许视图调整自身大小的约束?现在,我有viewForHeaderInSection:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if (section == 0) {
UIView *header = [UIView new];
UIView *headerBg = [UIView new];
UILabel *title = [UILabel new];
UILabel *distance = [UILabel new];
UILabel *desc = [UILabel new];
headerBg.translatesAutoresizingMaskIntoConstraints = NO;
title.translatesAutoresizingMaskIntoConstraints = NO;
distance.translatesAutoresizingMaskIntoConstraints = NO;
desc.translatesAutoresizingMaskIntoConstraints = NO;
[headerBg setBackgroundColor:[UIColor colorWithWhite:1.0 alpha:0.8]];
[title setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:14.0]];
[title setTextColor:kFONT_COLOUR];
NSString *address = _place.address ? (_place.address.length > 0 ? _place.address : @"Unknown Address") : @"Unknown Address";
[title setText:address];
[distance setFont:[UIFont fontWithName:@"HelveticaNeue" size:14.0]];
[distance setTextColor:kFONT_COLOUR];
[distance setText:@"Distance: ?m"];
[distance setTextAlignment:NSTextAlignmentRight];
[desc setFont:[UIFont fontWithName:@"HelveticaNeue" size:11.0]];
[desc setTextColor:kFONT_COLOUR];
[desc setNumberOfLines:0];
[desc setLineBreakMode:NSLineBreakByWordWrapping];
[desc setText:_place.desc ? (_place.desc.length > 0 ? _place.desc : @"No Description Given") : @"No Description Given"];
[headerBg addSubview:title];
[headerBg addSubview:distance];
[headerBg addSubview:desc];
NSDictionary *bindings = NSDictionaryOfVariableBindings(title, distance, desc, headerBg);
[headerBg addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-9-[title]-[distance(100)]-9-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:bindings]];
[headerBg addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-9-[desc]-9-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:bindings]];
[headerBg addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-9-[title(20)]-[desc]-|" options:NSLayoutFormatAlignAllLeading metrics:nil views:bindings]];
[header addSubview:headerBg];
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[headerBg]|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:bindings]];
[header addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerBg]-9-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:bindings]];
return header;
}
return nil;
}
任何帮助都会很棒:)