我要实现的是在其中包含UILabel的情况下自动调整单元格的大小。在开始拥抱部分之前,我一直能够使它工作。拥抱是指如果文本真的很短,则使UILabel尽可能小。
我准备了一个非常简单的例子来说明我的问题:
http://s000.tinyupload.com/index.php?file_id=11087347944522931899
当我将尾随约束设置为“ 500”优先级(低于然后是750)时,一切都很好。现在看来,尺寸调整单元正在减小UILabel的大小,但是从不增加,并且所有高度计算的确是错误的。
在第一个真正的短单元进入之后-在这个单元坏了之后所有的一切:
From debugging I found out that once UILabel hits 8px, it will gets bigger anymore and all height calculation are done for 8px width.
I found a work around and resetting preferredWidth after cell is dequeued for whatever reason helps, but I'm not sure if there are any better ways of solving the problem.
My workaround is comments in attached project (line 55, line 81) ChatTableController.m and I'm looking for proper solution for that.
Firstly, set the trailing constraint on your label to be >=20. This lets the label shrink.
Your real problem though is this method:
- (void)setBounds:(CGRect)bounds {
[super setBounds:bounds];
if (self.numberOfLines == 0 && bounds.size.width != self.preferredMaxLayoutWidth) {
self.preferredMaxLayoutWidth = self.bounds.size.width;
[self setNeedsUpdateConstraints];
}
}
You would be better to set cell.theLabel.preferedMaxLayoutWidth
when you create the cell in both heightForRowAtIndexPath
and cellForRowAtIndexPath
.
If you comment this code out completely it all seems to work.
You can also make your code work if you create a new prototype cell every time heightForRowAtIndexPath
is called. This is what led me to the above function.
It seems that every time heightForRowAtIndexPath
is called, the reuse of the prototype cell results in a combinatorial increase in height. You see this if you scroll down and back up.
So I would remove this method completely and let the constraints do the work for you. I see the cells shrink when one line to exact size and everything else compact.
Before you set the text in createCellForRowAtIndexPath add the following to make the layout width full screen minus your 20 margins:
cell.messageLabel.preferredMaxLayoutWidth=self.view.bounds.size.width-40;
and before you set the text in the prototype cells in heightForRowAtIndexPath:
prototypeCell.messageLabel.preferredMaxLayoutWidth=self.view.bounds.size.width-40;
设置preferredMaxLayoutWidth会导致旋转问题。设置每个单元格意味着每个单元格现在都具有特定于方向的约束。为了解决这个问题,您必须通过将以下内容添加到视图控制器中来在旋转时重新加载表:
- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[self.tableView reloadData];
}
最后结果:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句