To create a UICollectionView
that dynamically changes its size based on its contents, you will need to implement the UICollectionViewDelegateFlowLayout
protocol in your UIViewController
or UICollectionView
subclass.
Here is a sample code that will display 10 cells in a grid, with each cell's size determined dynamically based on its content.
main.swift2694 chars72 lines
In this example, we first create an instance of UICollectionViewFlowLayout
, then create a UICollectionView
instance with that layout. We then register a custom cell class called MyCell
. We then configure the UICollectionView
using Autolayout and set the data source and delegate to the view controller.
In numberOfItemsInSection
, we return 10, which is the number of cells we want to display. In cellForItemAt
, we dequeue a cell from the reuse pool, configure it with the appropriate data, and return it to be displayed on the screen.
In collectionView(_:layout:sizeForItemAt:)
, we calculate the size of each cell based on the width of the UICollectionView
and the height required to display the contents of the cell. In this example, we have set the height of each cell to be 100 points.
Finally, we define a custom cell class called MyCell
that displays a single label. We use Autolayout to add the label to the view hierarchy and pin it to the edges of the cell's contentView
.
gistlibby LogSnag