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:
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 yourUICollectionViewFlowLayout
: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]|
andV:|[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 theconstant
for those constraints in yourcellForRowAtIndexPath
method. But, to manage memory efficiently, you generally want to downsize the images to an appropriate size anyway, so this is generally not necessary.Alternatively, you can specify a delegate (a
UICollectionViewDelegateFlowLayout
) of the flow layout and then implementsizeForItemAt:
.