简体   繁体   中英

How to set constraints on a UICollectionViewCell?

I want my cell's width to be the same as the screen's width on every screen size. I can't set constraints in the storyboard since the option is greyed out, and setting them programmatically results in an error that says something like "Unable to activate constraint with anchors...because they have no common ancestor" even though I'm only setting the constraints to be the view's leading and trailing anchors.

The way the storyboard is setup now, the cell is at the desired width on iphone SE and that same width on the larger screen sizes.

This might help you to set the collectionView width same as the screen width. In your viewDidLoad() write this code

let height: CGFloat = 100.0 //Some constant
let width: CGFloat = self.view.frame.width

let spLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
spLayout.itemSize = CGSize(width: width, height: height)

you can use delegate method

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM