I have UITableViewCell subclass. The xib looks like below:

On launching the app I get the cell rendered as below as I change the content view with a custom lock view. The rotation from portrait to landscape is also done:

After rotating from landscape to portrait the layout is weird as below:

In the UITableViewCell subclass I have overridden the method systemLayoutSizeFitting(:withHorizontalFittingPriority:verticalFittingPriority:).
The implementation is as below:
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
print("customContentView.bounds:", customContentView.bounds)
verticalStackView.arrangedSubviews.forEach({
$0.sizeToFit()
$0.layoutIfNeeded()
})
verticalStackView.setNeedsLayout()
verticalStackView.layoutIfNeeded()
let customContentViewHorizontalPadding = customContentViewLeadingConstraint.constant + customContentViewTrailingConstraint.constant
let customContentViewVerticalPadding = customContentViewTopConstraint.constant + customContentViewBottomConstraint.constant
var _adjustedTargetSize = targetSize
_adjustedTargetSize.width -= customContentViewHorizontalPadding
_adjustedTargetSize.height -= customContentViewVerticalPadding
var size = customContentView.systemLayoutSizeFitting(_adjustedTargetSize)
let collectionViewContentSize = collectionView.collectionViewLayout.collectionViewContentSize
size.height += collectionViewContentSize.height
size.height += customContentViewVerticalPadding
size.width += customContentViewHorizontalPadding
return size
}
Upon testing the rotation from landscape to portrait I have found that the target size sent in to the method has a larger width then required for portrait, which results in a smaller height calculation and messing up the interface.
Why is the system passing in a larger width then required in this rotation?. How do I correct this?
Note: If I remove the override of the method the collection view inside the stack view seems to be totally ignored in the calculation as evident with the image below:


systemLayoutSizeFittingis not something you override, it’s something you call. And a stack view is already self sizing from its contents so your code would be pointless in any case. As this is a table cell, just configure constraints and let the runtime size the height.