Developing Auto Resizing Cells based on content using UIStackView in UICollectionView
AutoResizable UICollectionView Cells- FiltersUI
One of the best ways to achieve a horizontally scrollable Filters UI is by using UICollectionView
. A developers go-to is UICollectionView when it’s come to create a customised layout designs.
I personally use UICollectionView a lot because we can easily develop a complex layout designs using UICollectionView.
In this project, we are going to build a Filters UI Design using UICollectionView.
Filters UI Using CollectionView
While building Filter-UI, we are going to learn about:
How to make UICollectionView’s contentView auto resizable based on its superview
How to do selection and deselection in UICollectionView
Setup and Designing UICollectionView and it’s cells
Let’s get started by creating a new project in Xcode.
1. Storyboard Designing
To make CollectionView cells resizable set size estimated size as Automatic
Design a layout for
UICollectionView
cell’s FiltersUI
Add
UIStackView
to CollectionView cell to adjust the filter based on the content.Set
Alignment
,Distribution
andSpacing
for UIStackView
- Set all constraints of FiltersView to fill with UICollectionView Cell’s ContentView, so that whenever content of ViewFilter is increase Content View of UICollectionView also increase.
Auto Resizable UICollectionView Cell based on its content.
- In this above gif file you can see that UICollectionView Cell’s content View reacts based on its content.
2. Delegate for UICollectionView
FiltersUI — CollectionView Delegate Methods
- Here I have given
numberOfItems()
in section based on the numbers of filters that user needs. Here is sample input for filters:
var filters = [“Working Days”,”Attendance”,”Late”,”OT Permission”,”Excess Break”,”Excess Stay”,”Leave”,”Holidays”,”Present Days”]
3. Selection and Deselection— UICollectionView
Selection and Deselection Delegate Methods
To select an filter option, Use
didSelectItemAt()
delegate methods.When user select an filter cell, change filter text name’s label color and background of the cell
Make use
isSelected
property and set it as true when the particular cell is selected.Whenever user wants to choose another filter option, we need to deselect the cell which is already selected and also make sure we select the cell the user have clicked on.
To deselect before selection happens every time, use
didDeselectItemAt()
delegate methodDuring deselection change the text Color and background color to normal and user can do whatever filter option he needs.
Resources:
Find the detailed ScreenShots and project code in this Github link. You can refer to it in case you have any queries.
The Project is Updated for Xcode 11+ and Swift 5.0