AutoSizing cells: cell width equal to the CollectionView - ios

I'm using AutoSizing cells with Autolayout and UICollectionView.
I can specify constraints in code on cell initialization:
func configureCell() {
snp.makeConstraints { (make) in
make.width.equalToSuperview()
}
}
However, the app crashes as the cell hasn't been yet added to the collectionView.
Questions
At which stage of the cell's lifecycle it is possible to add a
constraint with cell's width?
Is there any default way of making a cell'swidthequal to the
widthof thecollectionViewwithout accessing an instance of
UIScreenorUIWindow`?
Edit
The question is not duplicate, as it is not about how to use the AutoSizing cells feature, but at which stage of the cell lifecycle to apply constraints to achieve the desired result when working with AutoLayout.

To implement self-sizing collection view cells you need to do two things:
Specify estimatedItemSize on UICollectionViewFlowLayout
Implement preferredLayoutAttributesFitting(_:) on your cell
1. Specifying estimatedItemSize on UICollectionViewFlowLayout
The default value of this property is CGSizeZero. Setting it to any other value causes the collection view to query each cell for its actual size using the cell’s preferredLayoutAttributesFitting(_:) method. If all of your cells are the same height, use the itemSize property, instead of this property, to specify the cell size instead.
This is just an estimate which is used to calculate the content size of the scroll view, set it to something sensible.
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 100)
2. Implement preferredLayoutAttributesFitting(_:) on your UICollectionViewCell subclass
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
// Specify you want _full width_
let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)
// Calculate the size (height) using Auto Layout
let autoLayoutSize = contentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: autoLayoutSize)
// Assign the new size to the layout attributes
autoLayoutAttributes.frame = autoLayoutFrame
return autoLayoutAttributes
}

You'll need to implement sizeForItemAt: to calculate the size.
We've also used a "sizing cell" if your cells have variable height. Eg:
class MyFancyCell: UICollectionViewCell {
class func cellSize(_ content: SomeContent, withWidth width: CGFloat) -> CGSize {
sizingCell.content = content
sizingCell.updateCellLayout(width)
return sizingCell.systemLayoutSizeFitting(UILayoutFittingExpandedSize)
}
fileprivate static let sizingCell = Bundle.main.loadNibNamed("ContentCell", owner: nil, options: nil)!.first as! ContentCell
func updateCellLayout(width: CGFloat) {
//Set constraints and calculate size
}
}

Related

UICollectionViewCell height not updating after changing it's contentView to reflect new height

I have a UICollectionView with self-sizing cells. All works fine. I have a like button inside the cell that when it is tapped, the global number of likes updates and change it's height accordingly.
Here I provide a video: https://vimeo.com/732687527
When I tap like and the height changes, it's not updated at runtime but if I fetch again the post, the cell has the correct height.
I did a little bit of debug and when the collectionView cells are fetched for the first time, they call the function inside the cell:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let autoLayoutAttributes = super.preferredLayoutAttributesFitting(layoutAttributes)
let targetSize = CGSize(width: layoutAttributes.frame.width, height: 0)
let autoLayoutSize = cellContentView.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.defaultLow)
let autoLayoutFrame = CGRect(origin: autoLayoutAttributes.frame.origin, size: CGSize(width: autoLayoutSize.width, height: autoLayoutSize.height + 40))
autoLayoutAttributes.frame = autoLayoutFrame
return autoLayoutAttributes
}
to calculate it's height automatically.
When I tap the like button, I set the cell viewModel with the new value and the cell configure function is called, updating the height and reflecting it
var viewModel: PostViewModel? {
didSet {
configure()
}
}
func configure() {
guard let viewModel = viewModel else { return }
//Bunch of cell configuration with the viewModel info
//Here I update the constraint of the element according to the like
if viewModel.postHasInfo {
postInfoView.constrainHeight(constant: 20)
} else {
postInfoView.constrainHeight(constant: 0)
}
}
ConstrainHeight function:
extension UIView {
func constrainHeight(constant: CGFloat) {
constraints.forEach {
if $0.firstAttribute == .height {
self.removeConstraint($0)
}
}
heightAnchor.constraint(equalToConstant: constant).isActive = true
layoutIfNeeded()
}
But even tho the configure method is called and it updates the cell view content as shown in the video, the cell height is not being updated as the preferredLayoutAttributesFitting method, which defines the cell height, is not getting called.
Is there any way to force this method getting called? I don't want to reload the cell/cells if it's not mandatory. I tried:
setNeedsLayout()
invalidateIntrinsicContentSize()
layoutIfNeeded()
layoutSubviews()
when the viewModel is set to see if preferredLayoutAttributesFitting is getting called again but without any luck.
Thanks in advance :D

Get dynamic height for UICollectionViewCell with custom layout

I need to create an UICollectionView with variable cell height but keeping a fixed vertical gap between cells. Something like this
I found a lot of examples, tutorials and libraries out there but all these need to implement a delegate method providing the height for each item.
My cells have a number of labels which can have one or more lines so I don't know in advance the final height of an element after the cell layouts its views.
Is there any way to achieve what I need?
You can calculate your cell height with systemLayoutSizeFitting function.
https://developer.apple.com/documentation/uikit/uiview/1622623-systemlayoutsizefitting
For example: (UICollectionViewCell is a subclass of UICollectionReusableView so you can use this for cell and header/footer too)
public extension UICollectionReusableView {
static func autoResizingView<T: UICollectionReusableView>(type: T.Type) -> T {
let nibViews = Bundle.main.loadNibNamed(T.identifier, owner: nil, options: nil)
return nibViews?.first as? T ?? T()
}
static func autoLayoutSize<T: UICollectionReusableView>(type: T.Type, targetWidth: CGFloat, configure: ((T) -> Void)?) -> CGSize {
let resizingView = UICollectionReusableView.autoResizingView(type: type)
resizingView.prepareForReuse()
configure?(resizingView)
resizingView.setNeedsLayout()
resizingView.layoutIfNeeded()
let targetSize = CGSize(width: targetWidth, height: 0)
let calculateView: UIView
if let contentView = (resizingView as? UICollectionViewCell)?.contentView {
calculateView = contentView
} else {
calculateView = resizingView
}
// Calculate the size (height) using Auto Layout
let autoLayoutSize = calculateView.systemLayoutSizeFitting(
targetSize,
withHorizontalFittingPriority: .required,
verticalFittingPriority: .defaultLow)
return autoLayoutSize
}
}

Collection View cells with full-width and dynamic height

I'm trying to create a feed of posts, like you'd see in the Twitter or Facebook app. From my understanding, I should be using a Collection View, so I've set one up.
But now, I'm confused as to how to make the cells full-width and the height of the cells dynamic, since the text within the cell can vary from just 1 line to many dozens of lines.
How would I go about doing this?
You may need UICollectionViewFlowLayout instance
let frame: CGRect = ...
let layout = UICollectionViewFlowLayout()
layout.estimatedItemSize = CGSize.zero
self.collectionView = UICollectionView(frame: someFrame, collectionViewLayout: layout)
About estimatedItemSize:
The default value of this property is CGSizeZero. Setting it to any other value causes the collection view to query each cell for its actual size using the cell’s preferredLayoutAttributesFitting(_:) method. If all of your cells are the same height, use the itemSize property, instead of this property, to specify the cell size instead.
Then you may design your UICollectionViewCell and in awakeFromNib() add an internal constraint to set exact width.
Then in cell for item at index path method you may do next:
let cell = ... as? MyCustomCell
cell?.load(model: someModel, widthConstraint: collectionView.bounds.width)
Important thing is to handle view size changes on rotation and split screen modes:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { _ in
self.collectionView.collectionViewLayout.invalidateLayout()
}) { _ in }
}
First that you would need is a UITextView.
Make sure it's scroll is disabled and you set the text content accordingly. For this open the Interface Builder, select the text view and there will be a section called "Scroll View". Uncheck Scrolling Enabled. This is very important so that UITextView skips the scrolling and stretches the content as much as required.
ViewController:
Secondly, in your ViewController you need to handle SubView Layout changes. This is called when rotation's are made or any size of the ViewController's view changes.
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let layout = self.collection.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: self.collection.frame.size.width-layout.sectionInset.left-layout.sectionInset.right-self.collection.contentInset.left - self.collection.contentInset.right, height: 100.0)
}
}
UICollectionViewCell Subclass:
Once you set the esitmatedItemSize, it's time to provider preferredLayoutAttributesFitting. You will have to override the UICollectionViewCell subclass.
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutAttributes.size = self.getCellHeight()
return layoutAttributes
}
func getCellHeight()->CGSize{
self.setNeedsDisplay()
self.layoutIfNeeded()
let size = self.contentView.systemLayoutSizeFitting(UILayoutFittingExpandedSize)
return size
}

How to adjust height of UICollectionView to be the height of the content size of the UICollectionView?

I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
but return self.collection.contentSize always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
I would suggest the following:
Add a height constraint to your collection view.
Set its priority to 999.
Set its constant to any value that makes it reasonably visible on the storyboard.
Change the bottom equal constraint of the collection view to greater or equal.
Connect the height constraint to an outlet.
Every time you reload the data on the collection view do the following:
You may also want to consider the Inset of the collection view by adding it to the content size.
Code Sample:
CGFloat height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
heightConstraint.constant = height
self.view.setNeedsLayout() Or self.view.layoutIfNeeded()
Explanation: Extra, You don't have to read if you understand it. obviously!!
The UI will try to reflect all the constraints no matter what are their priorities. Since there is a height constraint with lower priority of (999), and a bottom constraint of type greater or equal. whenever, the height constraint constant is set to a value less than the parent view height the collection view will be equal to the given height, achieving both constraints.
But, when the height constraint constant set to a value more than the parent view height both constraints can't be achieved. Therefore, only the constraint with the higher priority will be achieved which is the greater or equal bottom constraint.
The following is just a guess from an experience. So, it achieves one constrant. But, it also tries to make the error in the resulted UI for the other un-achieved lower priority constraint as lowest as possible. Therefore, the collection view height will be equal to the parent view size.
In Swift 5 and Xcode 10.2.1
My CollectionView name is myCollectionView
Fix height for your CollectionView
Create Outlet for your CollectionViewHeight
IBOutlet weak var myCollectionViewHeight: NSLayoutConstraint!
Use below code
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
myCollectionViewHeight.constant = height
self.view.layoutIfNeeded()
}
Dynamic width for cell based on text content...
Dynamic cell width of UICollectionView depending on label width
1) Set Fix Height of your CollectionView.
2) Create Outlet of this CollectionView Height Constant.
Like :
IBOutlet NSLayoutConstraint *constHeight;
3) Add below method in your .m file:
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGFloat height = collectionMenu.collectionViewLayout.collectionViewContentSize.height;
constHeight.constant = height;
}
I ended up, by subclassing the UICollectionView and overriding some methods as follows.
Returning self.collectionViewLayout.collectionViewContentSize for intrinsicContentSize makes sure, to always have the correct size
Then just call it whenever it might change (like on reloadData)
Code:
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return self.collectionViewLayout.collectionViewContentSize
}
But be aware, that you lose "cell re-using", if you display large sets of data, eventhough they don't fit on the screen.
This seemed like the simplest solution for me.
class SelfSizingCollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isScrollEnabled = false
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return contentSize
}
}
You may not need to override reloadData
You have to set height constraint as equal to content size
HeightConstraint.constant = collection.contentSize.height
Took the solution by d4Rk which is great, except in my case it would keep cutting off the bottom of my collection view (too short). I figured out this was because intrinsic content size was sometimes 0 and this would throw off the calculations. IDK. All I know is this fixed it.
import UIKit
class SelfSizedCollectionView: UICollectionView {
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
let s = self.collectionViewLayout.collectionViewContentSize
return CGSize(width: max(s.width, 1), height: max(s.height,1))
}
}
Subclass UICollectionView as follows
Delete height constraint if any
Turn on Intrinsic Size
-
class ContentSizedCollectionView: UICollectionView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: collectionViewLayout.collectionViewContentSize.height)
}
}
If you set the height constraint of the collection view. Just observe the contentSize change in the viewDidLoad and update the constraint.
self.contentSizeObservation = collectionView.observe(\.contentSize, options: [.initial, .new]) { [weak self] collectionView, change in
guard let `self` = self else { return }
guard self.collectionView.contentSize != .zero else { return }
self.collectionViewHeightLayoutConstraint.constant = self.collectionView.contentSize.height
}
I have a multi-line, multi-selection UICollectionView subclass where the cells are of fixed height and left-aligned flowing from left to right. It's embedded in a vertical stack view that's inside a vertical scroll view. See the UI component below the label "Property Types".
In order for the collection view to fit the height of its contentSize, here's what I had to do (note that this is all within the UICollectionView subclass):
Give the collection view a non-zero minimum height constraint of priority 999. Auto-sizing the collection view to its content height simply won't work with zero height.
let minimumHeight = heightAnchor.constraint(greaterThanOrEqualToConstant: 1)
minimumHeight.priority = UILayoutPriority(999)
minimumHeight.isActive = true
Set the collection view's content hugging priority to .required for the vertical axis.
setContentHuggingPriority(.required, for: .vertical)
Calling reloadData() is followed by the following calls:
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
For example, I have a setItems() function in my subclass:
func setItems(_ items: [Item]) {
self.items = items
selectedIndices = []
reloadData()
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
Override contentSize and intrinsicContentSize as follows:
override var intrinsicContentSize: CGSize {
return contentSize
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
}
Do following.
first set height constrain for UICollectionView
here calendarBaseViewHeight is UICollectionView height Variable
call the function after reload the collection view
func resizeCollectionViewSize(){
calendarBaseViewHeight.constant = collectionView.contentSize.height
}
first of all calculate number of cells than multiply it with height of cell and then return height in this method
collectionView.frame = CGRectMake (x,y,w,collectionView.collectionViewLayout.collectionViewContentSize.height); //objective c
//[collectionView reloadData];
collectionView.frame = CGRect(x: 0, y: 0, width: width, height: collectionView.collectionViewLayout.collectionViewContentSize.height) // swift
On your UICollectionView set your constraints such as Trailing, Leading, and Bottom:
If you look at my height constraint in more detail, as it is purely for storyboard look so I don't get errors, I have it to Remove at build time. The real height constraint is set in my code down below.
My code for DrawerCollectionView, which is set as the collection view Custom Class:
import UIKit
class DrawerCollectionView: UICollectionView {
override func didMoveToSuperview() {
super.didMoveToSuperview()
heightAnchor.constraint(equalToConstant: contentSize.height).isActive = true
}
}
Adjusting height of UICollectionView to the height of it's content size 🙌🏻
SWIFT 5
final class MyViewController: UIViewController {
// it's important to declare layout as separate constant due to late update in viewDidLayoutSubviews()
private let layout = UICollectionViewFlowLayout()
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupCollectionViewConstraints()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateFlowLayout()
}
private func setupCollectionView() {
view.addSubview(collectionView)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
collectionView.dataSource = self
}
private func setupCollectionViewConstraints() {
// your collectionView constraints setup
}
private func updateFlowLayout() {
let height = collectionView.collectionViewLayout.collectionViewContentSize.height
layout.itemSize = CGSize(width: view.frame.width, height: height)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = .zero
layout.minimumLineSpacing = .zero
layout.sectionInset = UIEdgeInsets.zero
}
}
extension MyViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {...}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {...}
}
work for me
let heightRes = resCollectionView.collectionViewLayout.collectionViewContentSize.height
foodHeightConstrant.constant = height.advanced(by: 1 )
foodCollectionView.setNeedsLayout()
foodCollectionView.layoutIfNeeded()
I was using a UICollectionView in UITableView cell. For me, the following solution worked.
In parent view of collection view, I updated the height constraint in layoutSubviews method like this
override func layoutSubviews() {
heightConstraint.constant = myCollectionView.collectionViewLayout.collectionViewContentSize.height
}
and then in cellForRowAtIndexpath, just before returning the cell, call this
cell.layoutIfNeeded()
The only solution worked for me when CollectionView is inside TableView custom cell is to
Subclass from ContentSizedCollectionView:
final class ContentSizedCollectionView: UICollectionView {
override var contentSize: CGSize{
didSet {
if oldValue.height != self.contentSize.height {
invalidateIntrinsicContentSize()
}
}
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric,
height: contentSize.height)
}
}
private let collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.sectionInset = UIEdgeInsets(top: 20, left: 17, bottom: 20, right: 17)
let collectionView = ContentSizedCollectionView(frame: .zero, collectionViewLayout: layout).prepareForAutoLayout()
return collectionView
}()
In UITableViewDelegate for TableView cell:
if let reusableCell = cell as? YourTableViewCell {
reusableCell.frame = tableView.bounds
reusableCell.layoutIfNeeded()
}
Remove height constraints of UICollectionView if any.
This article helped me a lot: https://medium.com/#ar.sarris/self-sizing-collectionview-inside-a-tableview-f1fd4f42c44d
Get the height of the cell. Something like this
let cellHeight = cell.frame.height
Get the origin of the collection view
let cvOrigin = collectionView.frame.origin
Get the width of the collection view
let cvWidth = collectionView.bounds.width
Set the frame of the content view
collection.frame = CGRect(x: cvOrigin.x, y: cvOrigin.y, width: cvWidth, height: cellHeight )

Resize UICollectionViewCell

In my app I have UICollectionView with FlowLayout (vertical). and in collection cell I have label for header and textView for content. Content length may be vary, short or long. I need to implement cell's autoresizing. in my CustomCell class I overrided this method:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
let attributes = layoutAttributes.copy() as! UICollectionViewLayoutAttributes
let desiredHeight = systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
attributes.frame.size.height = desiredHeight
return attributes
}
in ViewController class in viewDidLoad() I wrote this:
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.estimatedItemSize = CGSize(width: view.frame.width, height: 120)
}
app runs w/o any errors, but cell resizing only after scrolling, not when view appears on screen. is there any issue to fix that?
before scrolling
after scrolling
I believe that you have an update constraint issue, this is why when you scroll the content, you have the constraints already updated and get the right height. Before calling systemLayoutSizeFitting(UILayoutFittingCompressedSize).height you should call layoutIfNeeded()

Resources