UICollectionView won't center

Asked by At

I have a fullscreen UICollectionView with cells. I have checked the width and height, and the view covers the entire screen. However, when I enabled paging, the view was no longer centered. How can I set the center of the cell or the collection view, so it does take the entire screen?

import UIKit

class ShowPictures: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {

    var PICTURES: [Picture] = []

    @IBAction func swipeAway(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }

    override var prefersStatusBarHidden: Bool {
        return true
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }

    private func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return UIScreen.main.bounds.size
    }

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.PICTURES.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let item: Messages.MessageAdapter.Item.Picture = self.PICTURES[indexPath.section]
        let cell: Cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell

        return cell
    }

    @IBAction func CloseController(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }

}

class Cell: UICollectionViewCell, UIScrollViewDelegate {

    @IBOutlet weak var _image: UIImageView!
    @IBOutlet weak var _scroll: UIScrollView!

    override func layoutSubviews() {
        self._scroll.delegate = self
        self._scroll.zoomScale = CGFloat(integerLiteral: 1)
    }

    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return self._image
    }

}

1 Answers

0
André Slotta On Best Solutions

Add the following delegate method to remove the inset:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return .zero
}