【发布时间】:2014-06-17 08:40:22
【问题描述】:
我正在尝试学习自动布局,最后以为发生这种情况时我已经掌握了窍门。我正在玩原型单元格和标签。我正在尝试拥有一个
- 标题,
titleLbl- 图片中的蓝色框 - 钱,
moneyLbl- 图片中的绿框 - 字幕/说明,
subTitleLbl- 图片中的红框
到目前为止,我有这个:
我想要实现的是:
- 绿色框应始终完全显示在 1 行上
- 绿色框内的值应以蓝色框为中心
- 蓝色框将占用剩余空间(-8px 用于 2 之间的水平约束)并在必要时显示在多行上
- 红色框应位于下方,并根据需要显示尽可能多的行。
正如您所见,除了最后一行中的示例之外,这几乎都可以正常工作。我试图对此进行研究,据我所知,这与内在内容大小有关。网上很多帖子都推荐设置setPreferredMaxLayoutWidth,我已经在多个地方为titleLbl做了这个,但没有效果。仅当将其硬编码为180 时,我才得到结果,但它还在文本顶部/下方的其他蓝色框上添加了空白/填充,大大增加了红色/蓝色框之间的空间。
这是我的限制:
标题:
金钱:
字幕:
根据我使用其他文本示例运行的测试,它似乎使用了故事板中显示的宽度,但任何纠正它的尝试都不起作用。
我创建了一个单元格的 ivar 并用它来创建单元格的高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
[sizingCellTitleSubMoney.titleLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"title"]];
[sizingCellTitleSubMoney.subtitleLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"subtitle"]];
[sizingCellTitleSubMoney.moneyLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"cost"]];
[sizingCellTitleSubMoney layoutIfNeeded];
CGSize size = [sizingCellTitleSubMoney.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height+1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MATitleSubtitleMoneyTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifierTitleSubTitleMoney];
if(!cell)
{
cell = [[MATitleSubtitleMoneyTableViewCell alloc] init];
}
cell.titleLbl.layer.borderColor = [UIColor blueColor].CGColor;
cell.titleLbl.layer.borderWidth = 1;
cell.subtitleLbl.layer.borderColor = [UIColor redColor].CGColor;
cell.subtitleLbl.layer.borderWidth = 1;
cell.moneyLbl.layer.borderColor = [UIColor greenColor].CGColor;
cell.moneyLbl.layer.borderWidth = 1;
[cell.titleLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"title"]];
[cell.subtitleLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"subtitle"]];
[cell.moneyLbl setText:[[tableViewData objectAtIndex:indexPath.row] objectForKey:@"cost"]];
return cell;
}
我尝试在单元格的布局子视图中设置setPreferredMaxLayoutWidth:
- (void)layoutSubviews
{
[super layoutSubviews];
NSLog(@"Money lbl: %@", NSStringFromCGRect(self.moneyLbl.frame));
NSLog(@"prefferredMaxSize: %f \n\n", self.moneyLbl.frame.origin.x-8);
[self.titleLbl setPreferredMaxLayoutWidth: self.moneyLbl.frame.origin.x-8];
}
日志:
2014-04-30 21:37:32.475 AutoLayoutTestBed[652:60b] Money lbl: {{209, 20}, {91, 61}}
2014-04-30 21:37:32.475 AutoLayoutTestBed[652:60b] prefferredMaxSize: 201.000000
这是我所期望的,因为 2 个元素之间有 8px 并且控制台会验证这一点。无论我在蓝色框中添加多少文本,它都可以在第一行完美运行,这与情节提要相同,但是对绿色框的任何增加都会引发宽度计算。我也尝试根据其他问题的答案在tableView:willDisplayCell 和tableView:heightForRowAtIndexPath: 中进行设置。但无论如何它只是没有布局。
任何帮助、想法或 cmets 将不胜感激
【问题讨论】:
标签: ios objective-c uilabel autolayout uistoryboard