在 swift 中调整 UICollectionCell 大小的步骤

Steps involving in resizing UICollectionCell in swift

我正在研究自动布局和大小 class 已启用 project.I 尝试调整 UICollectionViewCell 宽度以确保它适合整个屏幕。

code:
 screenSize = UIScreen.mainScreen().bounds
 screenWidth = screenSize.width
    func collectionView(collectionView: UICollectionView,
            layout collectionViewLayout: UICollectionViewLayout,
            sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize{
                recentCollection.collectionViewLayout.invalidateLayout()
                return CGSizeMake(screenWidth, 200.0)
        }

我不知道我的工作方式是否正确?请提前提供帮助appreciated.thanks

只需将 UICollectionView 的宽度设置为 0 并在 viewdidload() 方法中更新约束

screenSize = UIScreen.mainScreen().bounds
screenWidth = screenSize.width
    var Constraint = NSLayoutConstraint(item: recentCollection, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: screenWidth)
    recentCollection.addConstraint(Constraint)

有一个数学技巧,您可以在不涉及约束的情况下使用!!!!

您将获得一个单元格 = 任何设备宽度!

数字 1 = 项目计数!您可以独立于您的总项目数调整它,以增加或减少屏幕中的项目!例如 / (Double(33)) on iPhone 4 将在 4 列中显示 33 个项目,每行 4 个项目!在 iPhone 6 Pluse 中,您会看到相同的图片单元格将按比例放大 4 列!

您可以使用此技巧根据屏幕尺寸或任何自动调整内容视图按比例动态调整视图和字体的大小!

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        var deviceSize = UIScreen.mainScreen().bounds.size
        var flexCell = sqrt(Double(deviceSize.width * deviceSize.height) / (Double(1)))

        return CGSize(width: flexCell , height: flexCell)

    }