简体   繁体   English

快速自定义集合视图单元格

[英]Custom Collection view cell in swift

I am new to iOS development and I am developing a buy/sell application. 我是iOS开发的新手,正在开发一个买卖应用程序。 I am trying to make a collection view where I don't hard set the size of the collection view cell. 我正在尝试创建一个集合视图,在这里我不会硬性设置集合视图单元格的大小。 Instead it would depend on the user who post up something they are selling. 取而代之的是,将取决于发布他们所销售商品的用户。 I realized that by hard coding the size of the boxes, everything looks "boxy". 我意识到,通过对盒子的大小进行硬编码,所有东西看起来都像“盒子”。 Any suggestions would be greatly appreciated. 任何建议将不胜感激。

Assuming you're using the default flow layout, there are two options: 假设您使用的是默认流布局,则有两个选项:

  1. You can have self-sizing cells if you: 如果满足以下条件,则可以具有自动调整大小的单元:

    • define unambiguous constraints between your cell and its subviews; 在单元格及其子视图之间定义明确的约束;

    • do not define fixed width/height constraints for the image view; 不要为图像视图定义固定的宽度/高度约束;

    • set the estimatedItemSize of your UICollectionViewFlowLayout : 设置estimatedItemSize您的UICollectionViewFlowLayout

       let layout = collectionView?.collectionViewLayout as! UICollectionViewFlowLayout layout.estimatedItemSize = CGSize(width: 100, height: 100) 

    Auto layout will then resize the image view to fit the image, and the cell will then resize itself to fit that, accordingly. 然后,自动布局将调整图像视图的大小以适合图像,然后单元格将调整自身的大小以适合该图像。 So, for example, with some random image sizes, the standard flow layout will resize the cells automatically for us: 因此,例如,对于一些随机的图像大小,标准流程布局将为我们自动调整单元格的大小:

    样品采集视图

    Now this is a simple cell with a randomly-sized, solid color image in an image view and constraints of H:|[imageView]| 现在,这是一个简单的单元格,在图像视图中具有随机大小的纯色图像,并且约束条件为H:|[imageView]| and V:|[imageView]| V:|[imageView]| , but the same idea works with complicated cells, too. ,但同样的想法也适用于复杂的单元格。 You just need to make sure that the top/bottom and leading/trailing constraints of the cells are unambiguous. 您只需要确保单元格的顶部/底部和前/后约束是明确的即可。

    Note, if you rely upon the implicit size of the image view, this assumes of course that the images are already sized consistently for the device. 请注意,如果您依赖图像视图的隐式大小,则当然会假设设备的图像大小已经一致。 If not, you might want to create constraints for the image view height/width, include @IBOutlet references for that, and then set the constant for those constraints in your cellForRowAtIndexPath method. 如果不是,则可能要为图像视图的高度/宽度创建约束,包括@IBOutlet引用,然后在cellForRowAtIndexPath方法中为这些约束设置constant But, to manage memory efficiently, you generally want to downsize the images to an appropriate size anyway, so this is generally not necessary. 但是,为了有效地管理内存,通常无论如何都希望将图像缩小到适当的大小,因此通常没有必要。

  2. Alternatively, you can specify a delegate (a UICollectionViewDelegateFlowLayout ) of the flow layout and then implement sizeForItemAt: . 或者,您可以指定流布局的委托( UICollectionViewDelegateFlowLayout ),然后实现sizeForItemAt:

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

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