Reputation: 37
let numberOfCellsPerRow: CGFloat = 3
override func viewDidLoad() {
super.viewDidLoad()
layout = UICollectionViewFlowLayout()
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
view.addSubview(collectionView)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1) * layout.minimumInteritemSpacing) / numberOfCellsPerRow
return CGSize(width: cellWidth, height: 75.0)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
itemCell.backgroundColor = .black
return itemCell
}
Vertical Orientation
Horizontal Orientation
I'm expecting all cells on the same row. Why there is some margin on the left side of the first cell (horizontal orientation)? In the case when I'm launching the application with horizontal orientation, some space appears between cells in vertical orientation.
Upvotes: 1
Views: 439
Reputation: 100503
You can try to use auto-layout
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
])
Or refresh the frame inside viewWillTransition
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
self.collectionView.collectionViewLayout.invalidateLayout()
}
Upvotes: 1