快速自定义集合视图单元格 [英] Custom Collection view cell in swift

查看:76
本文介绍了快速自定义集合视图单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是iOS开发的新手,并且正在开发买卖应用程序.我正在尝试创建一个集合视图,在这里我不会硬性设置集合视图单元格的大小.取而代之的是,它取决于发布他们所销售商品的用户.我意识到,通过对箱子的大小进行硬编码,所有东西看起来都像箱子".任何建议将不胜感激.

I am new to iOS development and I am developing a buy/sell application. 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. 如果您具有以下条件,则可以设置自定义尺寸的单元格:

  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;

设置UICollectionViewFlowLayoutestimatedItemSize:

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:

现在这是一个简单的单元格,在图像视图中具有随机大小的纯色图像,并且约束H:|[imageView]|V:|[imageView]|,但是相同的想法也适用于复杂的单元格.您只需要确保单元格的顶部/底部和前/后约束是明确的即可.

Now this is a simple cell with a randomly-sized, solid color image in an image view and constraints of H:|[imageView]| and 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.

请注意,如果您依赖图像视图的隐式大小,则这当然假定图像已针对设备进行了一致的调整.如果不是,则可能要为图像视图的高度/宽度创建约束,为此添加@IBOutlet引用,然后在cellForRowAtIndexPath方法中为这些约束设置constant.但是,为了有效地管理内存,通常无论如何都希望将图像缩小到适当的大小,因此通常没有必要.

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. But, to manage memory efficiently, you generally want to downsize the images to an appropriate size anyway, so this is generally not necessary.

或者,您可以指定一个委托( UICollectionViewDelegateFlowLayout ),然后实施 sizeForItemAt: .

Alternatively, you can specify a delegate (a UICollectionViewDelegateFlowLayout) of the flow layout and then implement sizeForItemAt:.

这篇关于快速自定义集合视图单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆