如何以编程方式设置UICollectionViewCell宽度和高度

JVS*_*JVS 63 uicollectionview swift

我正在努力实现一个CollectionView.当我使用Autolayout时,我的细胞不会改变大小,而是改变它们的对齐方式.

现在我宁愿将其大小改为例如

//var size = CGSize(width: self.view.frame.width/10, height: self.view.frame.width/10)
Run Code Online (Sandbox Code Playgroud)

我尝试过设置我的 CellForItemAtIndexPath

collectionCell.size = size
Run Code Online (Sandbox Code Playgroud)

它虽然没有用.

有没有办法实现这个目标?

编辑:

似乎答案只会改变我的CollectionView宽度和高度本身.约束中是否存在冲突?有什么想法吗?

Pin*_*Gjr 116

使用此方法设置自定义单元格高度宽度.

确保添加此协议

UICollectionViewDelegate

UICollectionViewDataSource

UICollectionViewDelegateFlowLayout
Run Code Online (Sandbox Code Playgroud)

Objective-C的

@interface YourViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
}
Run Code Online (Sandbox Code Playgroud)

Swift 4或更高版本

extension YourViewController: UICollectionViewDelegate {
    //Write Delegate Code Here
}

extension YourViewController: UICollectionViewDataSource {
    //Write DataSource Code Here
}

extension YourViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: screenWidth, height: screenWidth)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我已经习惯了以编程方式完成所有事情,现在这对我来说似乎很陌生。在 Storyboard 将 **Estimated Size** 设置为 **None** 并添加 **UICollectionViewDelegateFlowLayout** 是有什么用的 (12认同)
  • 将“估计大小”设置为“无”对我有用。谢谢@PinkeshGjr (8认同)
  • 将“估计大小”设置为“无”拯救了我的日子。 (8认同)
  • 我很高兴我找到了这个,我浪费了 2 个小时来追这个,结果却学会了神奇的“估计尺寸” (7认同)

Spy*_*ydy 79

如果使用故事板并覆盖UICollectionViewDelegateFlowLayout那么在 swift 5 和 Xcode 11 中也将估计大小设置为无 在此处输入图片说明

  • 将估计大小设置为无修复了所有问题 (4认同)
  • 很好修复。这是我根据[Apple的文档](https://developer.apple.com/documentation/uikit/uicollectionviewflowlayout/1779556-automaticsize)对此问题的诊断:当`UICollectionViewFlowLayout`似乎默认`estimatedItemSize`为`UICollectionViewFlowLayout.automaticSize`时使用 IB,尽管文档说它应该默认为“CGSizeZero”。正如 Apple 所说,“automaticSize”“为您的集合视图启用自动调整单元格大小”。这就是为什么 IB 中的其他大小变化不起作用。 (3认同)
  • 这很有帮助。谢谢!! (2认同)
  • 谢谢将估计大小设置为未解决的问题 (2认同)

pie*_*e23 65

确保UICollectionViewDelegateFlowLayoutclass声明中添加协议

class MyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout
{
    //MARK: - UICollectionViewDelegateFlowLayout

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
       return CGSize(width: 100.0, height: 100.0)
    }
}
Run Code Online (Sandbox Code Playgroud)


sab*_*uro 20

终于得到了答案.你应该扩展UICollectionViewDelegateFlowLayout
这应该与上面的答案一起使用.


Sup*_*.Ia 14

迅捷4.1

您有两种方法可以更改CollectionView的大小.
第一种方法 - >添加这个协议UICollectionViewDelegateFlowLayout
for在我的情况下,我想将单元格划分为一行中的3个部分.我在下面做了这个代码

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
            // In this function is the code you must implement to your code project if you want to change size of Collection view
            let width  = (view.frame.width-20)/3
            return CGSize(width: width, height: width)
    }

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }
        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

第二种方式 - >你不必添加UICollectionViewDelegateFlowLayout但你必须在viewDidload函数中编写一些代码而不是下面的代码

class ViewController: UIViewController {
@IBOutlet weak var collectionView1: UICollectionView!
        var collectionData = ["1.", "2.", "3.", "4.", "5.", "6.", "7.", "8.", "9.", "10.", "11.", "12."]

    override func viewDidLoad() {
        super.viewDidLoad()
        let width = (view.frame.width-20)/3
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = CGSize(width: width, height: width) 
    }
}
Run Code Online (Sandbox Code Playgroud)


extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource {


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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath)
        if let label = cell.viewWithTag(100) as? UILabel {
            label.text = collectionData[indexPath.row]
        }

        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)

无论你编写代码作为第一种方式还是第二种方式,你都会得到与上面相同的结果.我写的. 它对我有用

在此输入图像描述

  • 直接来自 raywenderlich.com (4认同)

Ant*_*Pak 8

尺寸比例根据iPhone尺寸:

以下是关于iPhone尺寸的细胞宽度和高度的不同之处:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}
Run Code Online (Sandbox Code Playgroud)

也许您还应该禁用对单元格的AutoLayout约束,以使此答案起作用.


mat*_*att 7

集合视图有一个布局对象.在您的情况下,它可能是一个流布局(UICollectionViewFlowLayout).设置流布局的itemSize属性.

  • 嗯,这完全取决于_when_你做到了.你没有展示你的真实代码,所以谁知道你在做什么?我保证你确实有效. (2认同)

小智 5

swift4 swift 4 ios 集合视图 collectionview 示例 xcode 最新代码工作示例

将此添加到顶部的委托部分

UICollectionViewDelegateFlowLayout

并使用此功能

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 20) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}
Run Code Online (Sandbox Code Playgroud)

///// 示例完整代码

在情节
提要中的集合视图和集合视图单元格上创建将集合引用为@IBOutlet 弱变量 cvContent: UICollectionView!

将此粘贴到视图控制器中

 import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    var arrVeg = [String]()
    var arrFruits = [String]()
    var arrCurrent = [String]()
    
    @IBOutlet weak var cvContent: UICollectionView!
    
  
    
    override func viewDidLoad() {
        super.viewDidLoad()
        arrVeg = ["Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato"]
        
        arrVeg = ["Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange"]
        
        
        arrCurrent = arrVeg
    }
    //MARK: - CollectionView
    


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (self.view.frame.size.width - 20) / 3 //some width
        let height = width * 1.5 //ratio
        return CGSize(width: width, height: height)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {

        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        
        return arrCurrent.count
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
        cell.backgroundColor =  UIColor.green
        return cell
    }
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*ari 5

Swift3Swift4中,您可以通过添加UICollectionViewDelegateFlowLayout并实现如下方式来更改单元格大小:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 100)
    }
Run Code Online (Sandbox Code Playgroud)

或者,如果以编程方式创建UICollectionView,则可以这样进行:

    let layout = UICollectionViewFlowLayout()
                    layout.scrollDirection = .horizontal //this is for direction
                    layout.minimumInteritemSpacing = 0 // this is for spacing between cells
                    layout.itemSize = CGSize(width: view.frame.width, height: view.frame.height) //this is for cell size
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
Run Code Online (Sandbox Code Playgroud)