简体   繁体   English

如何在UICollectionViewCell上设置约束?

[英]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. 现在设置情节提要的方式是,单元格在iphone SE上处于所需的宽度,在较大的屏幕尺寸上处于相同的宽度。

This might help you to set the collectionView width same as the screen width. 这可以帮助您将collectionView宽度设置为与屏幕宽度相同。 In your viewDidLoad() write this code 在您的viewDidLoad()编写此代码

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
        )
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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