Custom Collection view cell in swift

2019-09-14 06:35发布

问题:

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.

回答1:

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:

      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]| 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.

    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.

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