如何控制集合视图单元格布局的大小 swift 故事板

how to control the size of the collection view cell layout swift storyboard

我是初学者,不介意我的编码和英语我希望你能帮助我解决这个你甚至可能会觉得很傻的问题。 我一直面临调整单元格大小的问题。 看了几个youtube教程还是没找到解决办法!!

I changed the sizes here

I also tried and changed it in the cell (the book picture is actually a button)

and here is the output. so how can I resize it? I want it to be 2 columns

这是代码

class resViewViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource
    {
            func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
                return CGSize(width: 140, height: 180)
            }


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

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

            let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! resourceCellCollectionViewCell
            cell.name.text = resourcesName[indexPath.row]
            return cell
        }

the new output after fixing the code

我认为您要找的 class 是 UICollectionViewDelegateFlowLayout。您的 UICollectionView 有一个委托,委托可以实现 UICollectionViewDelegateFlowLayout 协议。在该实现中,您可以通过实现

来指定单元格的大小
collectionView(_:layout:sizeForItemAt:)

所以我希望你上面的代码是这样的:

class resViewViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 140, height: 180)
    }

请注意,class 实现了 UICollectionViewDelegateFlowLayout 协议,而不仅仅是 UICollectionViewDelegate

然后,在您的布局中,您需要设置单元格中包含的视图的自动调整大小掩码,使其随单元格本身一起缩小或增大