How is it possible that UITableViewCellContentView height is different from heightForRowAtIndexPath:

妖精的绣舞 提交于 2019-11-30 01:49:25
Talal MAZROUI

I found the answer here : Auto layout constraints issue on iOS7 in UITableViewCell

We just have to set the AutoresizingMask of the contentView to UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth and ... problem solved!

You could try to set the (/some) heights at a lower priority (e.g. @900). I had a similar issue (my UITableViewCellContentView was too small and the constraints could not be satisfied). After I lowered the priority of my "wrong" height it was laying out nicely at the intended heights.

You have to turn off autoresizing conversion for the view that contains your constraints if you add your constraints with code or visual language:

    [self.someView setTranslatesAutoresizingMaskIntoConstraints:NO];

This prevents the [UITableViewCellContentView:0x1ef2bf50(147)] constraint from being created.

In cellForRowAtIndexPath you request a cell from the tableview. The cell you get will either be a newly created cell (with size 320,44) or a cell that has been dequeued and sent the prepareForReuse message (with whatever size it had previously). When you apply code NSLayoutConstraints to the contentView they are resolved before the cell fits itself to the tableview space provided. This makes no sense but is definitely the conclusion of my observations.

So, in my instance I was getting new cells with 44 height but one of my constraints was for a fixed height of 48. This was throwing exceptions constantly and making debugging a pain. All I did to make the exceptions go away was to set the frame of the cell to the correct height (and width I suppose if you are experiencing issues on the horizontal dimension) when I was preparing it in cellForRowAtIndexPath.

UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// If the cell is new its frame will be (0,0,320,44)
cell.frame = CGRectMake(0,0,tableview.frame.size.width,calculatedHeightRequiredForLayout);
[cell.contentView addConstraints:constraints];

The cell will automatically resize itself to the correct dimensions before it displays in the tableview so you won't cause any issues, but your layout constraints will be applied without 'needing to be broken' by iOS...

I once struggled with something similar. Tried bazzilion of solutions. Nothing worked. And at the and I noticed that accidentally I created a cell in designer as UICollectionViewCell instead of UITableViewCell.
Just in case anyone would ever fill the same pain, check that too

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!