[英]Variable cell height in iOS UITableView with auto layout constraints in code
[英]iOS 7/8 UITableView Cell: Two UILabels with dynamic height with auto layout for variable row height
因此,當我只有一個標簽根據字符串的長度更改高度時,我可以使用自動布局設置動態高度大小。 我的問題是,如果我添加另一個應該做同樣的UILabel,事情就不會有效。
我將內容擁抱優先級和壓縮阻力設置為1000 = =我得到歧義警告
如果我將第二個UILabel的內容擁抱(垂直)設置為999或250,那么它的效果很好但僅當第二個標簽有2行或更多行時才能正常工作。 如果第二個標簽為空或只有一行,則heightForRowAtIndexPath systemLayoutSizeFittingSize:UILayoutFittingCompressedSize高度返回較大的值,並且單元格具有較大的空格。
我還玩了內在尺寸:默認或占位符(有幾個高度和寬度),但它也沒有幫助。
有什么建議可以做什么?
我終於開始工作了。 解決方案是我明確地將首選寬度設置為當前幀寬度。 因此,基本上檢查大小檢查器中“標簽”>“首選寬度”中的“顯式”復選標記。
參考: http : //www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout下載示例代碼並查看故事板設置。
對我來說,它結合了幾件事。
UILabel子類最終看起來像這樣:
@implementation LabelDynamicHeight
- (void)layoutSubviews
{
[super layoutSubviews];
self.preferredMaxLayoutWidth = self.frame.size.width;
[super layoutSubviews];
}
- (void)setBounds:(CGRect)bounds
{
[super setBounds:bounds];
if (self.numberOfLines == 0)
{
CGFloat boundsWidth = CGRectGetWidth(bounds);
if (self.preferredMaxLayoutWidth != boundsWidth)
{
self.preferredMaxLayoutWidth = boundsWidth;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize)intrinsicContentSize
{
CGSize size = [super intrinsicContentSize];
if (self.numberOfLines == 0)
{
// There's a bug where intrinsic content size may be 1 point too short
size.height += 1;
}
return size;
}
@end
除了在獲取tableView heightForRowAtIndexPath:
的高度之前在單元格上調用layoutIfNeeded systemLayoutSizeFittingSize:
在contentView上使用systemLayoutSizeFittingSize:
方法之前使約束准備就緒。 看起來像這樣:
- (CGFloat)tableView:( UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = ...;
CGFloat height = cell.frame.size.height;
if (cell.dynamicHeight)
{
// https://stackoverflow.com/a/26351692/1840269
[cell layoutIfNeeded];
height = cell.frame.size.height;
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
if (size.height > height)
height = size.height;
}
return height;
}
參考文獻:
對我來說,將內容擁抱優先級和內容壓縮阻力優先級設置為低於正常工作的元素之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.