Custom UIView in UITableView cells with UITableViewAutomaticDimension enabled
Asked Answered
C

0

7

I have UITableView with UITableViewAutomaticDimension and some estimatedRowHeight. For this table I am using custom UITableViewCell which contains some label and custom UIView with overridden intrinsicContentSize(). Constraints setup is correct and table is able to determine actual height for each row. So far so good.

Now I started to modify internal logic of my custom view to adapt it's appearance based on available width i.e. when table cell size is not wide enough my view can rearrange subviews to fit new limitation and this have impact to resulting height, so I have code like that:

var internalSize: CGSize = ...

override func intrinsicContentSize() -> CGSize {
    return internalSize
}

override func layoutSubviews() {
    super.layoutSubviews()
    fitIntoWidth(frame.size.width)
}

private func fitIntoWidth(width: CGFloat) {
    let height = // calculate based on content and width
    internalSize = CGSizeMake(width, height)
    invalidateIntrinsicContentSize()
}

Now, when I populate table view, intrinsicContentSize() returns some desired value but it is not good fit for current layout, then control goes to layoutSubviews() where size get recalculated and system again calls intrinsicContentSize() and now it returns good value. However, first time table loads data and cell heights calculated based on incorrect intrinsicContentSize() values. If I call reloadData() again all becomes fine and layout is also ok for all upcoming cells in table.

Where is my mistake and how to modify code to make cell sizing work correctly without calling reloadData() twice?

Chivalric answered 26/5, 2016 at 12:3 Comment(10)
why are you overriding the intrinsic size?Declare
@Declare because default implementation doesn't provide any information about view's size and in that case you should explicitly set height constraint to view. But I want some implementation like in UILabel - you just set it's text and never height - label itself calculates desired sizeChivalric
how about [cell layoutIfNeeded]; just before returning cell in cellForRow.. methodUnderlinen
@Alok nothing changes. I think that I should change something inside the custom view itself, because cells only with labels work fine without any additional calls to layout outsideChivalric
so basically with the override intrinsic size you are calculating UIView size ? can not it be done through systemLayoutSizeFittingSize or with CGRectGetMaxY and CGRectGetMaxXUnderlinen
@Alok systemLayoutSizeFittingSize not get called at all. And docs also mentions intrinsic content sizeChivalric
can you also show code for heightForRowMethod ?Underlinen
Let us continue this discussion in chat.Chivalric
Did you manage to solve this issue?Shuman
@Shuman just manual calculations using all delegate methods to report exact values, without automatic row height modeChivalric

© 2022 - 2024 — McMap. All rights reserved.