Salman500
Salman500

Reputation: 1211

UICollectionView full width and height problem

UICollectionView width is not full width, One cell per row

UICollectionView

private func setCollectionView() {

    let layout = UICollectionViewFlowLayout()
    layout.minimumInteritemSpacing = 0
    layout.minimumLineSpacing = 0
    layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    layout.scrollDirection = .horizontal

    collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    collectionView.showsHorizontalScrollIndicator = false
    collectionView.translatesAutoresizingMaskIntoConstraints = false
    collectionView.isPagingEnabled = true
    collectionView.register(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "cell")

}

UICollectionView -> Constraint

    NSLayoutConstraint.activate([
        view.leadingAnchor.constraint(equalTo: collectionView.leadingAnchor),
        view.trailingAnchor.constraint(equalTo: collectionView.trailingAnchor),
        view.topAnchor.constraint(equalTo: collectionView.topAnchor),
        view.bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
    ])

UIColletionViewCellSize

By adding UICollectionViewFlowLayoutDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width, height: collectionView.frame.height)
}

ImageCollectionViewCell

class ImageCollectionViewCell: UICollectionViewCell {
....
    private let imageView: UIImageView = {
        let img = UIImageView()
        img.contentMode = .scaleAspectFill
        img.translatesAutoresizingMaskIntoConstraints = false
        return img
    }()
....
}

ImageCollectionViewCell -> imageView Constraint

   addSubview(imageView)

    NSLayoutConstraint.activate([
        leadingAnchor.constraint(equalTo: imageView.leadingAnchor),
        trailingAnchor.constraint(equalTo: imageView.trailingAnchor),
        topAnchor.constraint(equalTo: imageView.topAnchor),
        bottomAnchor.constraint(equalTo: imageView.bottomAnchor)
    ])

UICollectionView FlowLayout Warning

The item height must be less than the height of the UICollectionView minus the section insets top and bottom values, minus the content insets top and bottom values.

The relevant UICollectionViewFlowLayout instance is , and it is attached to ; layer = ; contentOffset: {0, -44}; contentSize: {0, 0}; adjustedContentInset: {44, 0, 34, 0}> collection view layout: .

This is Keep Happening

https://gph.is/g/EqNL8jr

Upvotes: 0

Views: 1300

Answers (1)

Salman500
Salman500

Reputation: 1211

UICollectionView Warning Fix

    if #available(iOS 11.0, *) { collectionView.contentInsetAdjustmentBehavior = .never } 
    else { automaticallyAdjustsScrollViewInsets = false } 

Scale to fill was giving bigger image than UIImageView size

    img.clipsToBounds = true

Upvotes: 1

Related Questions