I have to make one collection view so that irrespective of iphone size we have just 2 images in each row and also we need border between each row and column as shown in the
Implement the following functions from collectionView's protocol:
// cell size
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)
}
...where view is your controller's (super) view
// inter-spacing
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
func collectionView(collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 2.0
}
Swift 4.* and Xcode 9.3
If you are using multiple collectionView on same ViewController then you can use something as below -
// Height and Width for the cell
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
if collectionView.tag == 101 {
return CGSize(width: 60, height: 60)
}
else if collectionView.tag == 102 {
return CGSize(width: view.frame.size.width/2, height: view.frame.size.width/2)
}
else {
return CGSize(width: 50, height: 50)
}
}
// InterItemSpacing
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if collectionView.tag == 101 {
return 5.0
}
else if collectionView.tag == 102 {
return 0.0
}
else {
return 5.0
}
}
// InterLineSpacing
func collectionView(_ collectionView: UICollectionView, layout
collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
if collectionView.tag == 101 {
return 5.0
}
else if collectionView.tag == 102 {
return 0.0
}
else {
return 5.0
}
}
Try this code. Just a different approach.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 6, left: 4, bottom: 6, right: 4)
layout.minimumInteritemSpacing = 04
layout.minimumLineSpacing = 04
layout.invalidateLayout()
return CGSize(width: ((self.view.frame.width/2) - 6), height: ((self.view.frame.width / 2) - 6))
}
Output from above code on different devices.