I am new in swift, here is a solution to make a CollectionView with 4 cell in screen and in below line I said 15 margin for each side this working for left and right but this not working for top and button
return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
, How could we have same margin on top and bottom ?
Here is MainViewController :
import UIKit
class MainViewController: UIViewController , UICollectionViewDelegate, UICollectionViewDataSource {
var listArray : [String] = []
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
print("MainViewController")
collectionView.delegate = self
collectionView.dataSource = self
for index in 1 ..< 12 {
listArray.append("Cell \(index)")
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "mainCell", for: indexPath) as! MainCollectionViewCell
let cellIndex = indexPath.item
cell.cellLabelText.text = listArray[cellIndex]
cell.backgroundColor = UIColor.blue
return cell
}
}
extension MainViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let bounds = collectionView.bounds
return CGSize(width: (bounds.width / 2 ) - 30 , height: ( bounds.height / 2 ) - 30 )
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
}
Here is MainCollectionViewCell :
import UIKit
class MainCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var cellLabelText: UILabel!
}