How to arrange collectionview cells closely according to text in swift

Viewed 70

I have given collectionview constraints

 height = 50, leading = trailing = top = 10

i have taken label inside containerview in cell

cell containerview constraints

 bottom = top = 5, horizontal center

label constraints with containerview

 leading = trailing = top = bottom = 5

code in didload:

   let serviceLayout = UICollectionViewFlowLayout()
    serviceLayout.minimumInteritemSpacing = 0
    serviceLayout.minimumLineSpacing = 0
    serviceLayout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
          self.servicesCollectionView.collectionViewLayout = serviceLayout

i am getting like this i need one near by another

enter image description here

i need like this

enter image description here

how do i get collectionview cells near by one another, pls do help

2 Answers

Try to use this custom Layout

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) ->     [UICollectionViewLayoutAttributes]? {

guard let oldAttributes = super.layoutAttributesForElements(in: rect) else {
    return super.layoutAttributesForElements(in: rect)
}

let spacing = CGFloat(6)

var newAttributes = [UICollectionViewLayoutAttributes]()
var leftMargin = self.sectionInset.left
for attributes in oldAttributes {
    if attributes.representedElementCategory == .supplementaryView {
        newAttributes.append(attributes)
    } else {
        if (attributes.frame.origin.x == self.sectionInset.left) {
            leftMargin = self.sectionInset.left
        } else {
            var newLeftAlignedFrame = attributes.frame
            newLeftAlignedFrame.origin.x = leftMargin
            attributes.frame = newLeftAlignedFrame
        }
        leftMargin += attributes.frame.width + spacing
        newAttributes.append(attributes)
    }
}
return newAttributes
}
}

Select your collection view in storyboard

  • Go to size inspector
  • Set scrollview indicator insets left and right as follows

enter image description here

Related