Let's begin
Full source code in GitHub
Step 1
In class SquareView : UIView the key is to define a "property called preferredMaxLayoutWidth, which specifies the maximum line width for calculating the intrinsic content size.
Since we usually don't know this value in advance, we need to take a two-step approach to get this right. First we let Auto Layout do its work, and then we use the resulting frame in the layout pass to update the preferred maximum width and trigger layout again."
override func layoutSubviews() {
super.layoutSubviews()
preferredMaxLayoutWidth = self.frame.size.width
invalidateIntrinsicContentSize()
setNeedsDisplay()
super.layoutSubviews()
}
Step 2
Now that we have our preferredMaxLayoutWidth we can compute the intrinsicContentSize:
override var intrinsicContentSize: CGSize {
let width = squareHeight * CGFloat(squares) + padding * CGFloat(squares) + padding
if width < preferredMaxLayoutWidth {
let height = squareHeight + padding + padding
let size = CGSize(width: width, height: height)
return size
}
else {
let vertSquares = ceil((width / preferredMaxLayoutWidth))
let height = squareHeight * vertSquares + padding * vertSquares + padding
let size = CGSize(width: preferredMaxLayoutWidth, height: height)
return size
}
}
Step 3
In the class SquareCell: UITableViewCell we have to force the layout of all subviews, which updates self's intrinsic height, and thus height of a cell. The key thing is to call super at the end (NOT at the beginning)
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
self.setNeedsLayout()
self.layoutIfNeeded()
return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority)
}
Learn more: UITableViewCell with intrinsic height based on width
Step 4
In the class SquareViewController: UIViewController make sure to reload the table when the orientation changes to landscape:
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animate(alongsideTransition: { (context) in
guard let windowInterfaceOrientation = self.windowInterfaceOrientation else { return }
if windowInterfaceOrientation.isLandscape {
self.myTableView.reloadData()
}
})
}
This is it!
Now enjoy creating custom UIViews that auto adjust to your table view cells!
Post
Replies
Boosts
Views
Activity
Solved:
On safari, go to preferences -> privacy.
Uncheck "Prevent cross-site tracking".
Reload the page and the "agree" button should appear.
I requested the feedback
https://feedbackassistant.apple.com/feedback/8456386