Custom Tag View Using UICollectionView

Jerry PM
4 min readJan 5, 2025

With Left-Aligned Layout

Design by Author

For the custom TagView in this code, it will be created using a UICollectionView without using any libraries, pods, or similar tools.

I took this example from a project I am currently working on, where I am required to customize this TagView according to the provided design.

When customizing the TagView, the required specifications are as follows:

  • The view should dynamically adjust to the length of the text.
  • The spacing between views is 8 points.
  • The views should align to the left (extra space will appear on the right side).
  • If the items exceed one row, the layout should adjust dynamically.

The first thing to do is to create a custom “UICollectionViewFlowLayout,” which I named “LeftAlignedFlowLayout.”

This is used to align the items to the left in the UICollectionView.

import UIKit

class LeftAlignedFlowLayout: UICollectionViewFlowLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
guard let attributes = super.layoutAttributesForElements(in: rect) else { return nil }

var leftMargin: CGFloat = sectionInset.left
var lastYPosition…

--

--

No responses yet