When displaying data with Uicollectionview, sometimes we want to adjust the cell spacing to a value we want, and then look at the API to see a property like this:
-(CGFloat) minimuminteritemspacing { return 0;}
However, in many cases we will find that this does not satisfy our requirements, and there is still a gap between cells that does not know how to produce.
We know that the cell spacing is determined by the size of the cell itemsize and the indent sectioninset of the section, and through these two data, Uicollectionview dynamically places the cell in the appropriate location, However, even if we continue to invoke the inset method, it is useless.
-(uiedgeinsets) sectioninset{ return uiedgeinsetsmake (0, 0, 0, 0);}
< note: What I want to achieve is 0 spacing, other things like >
As you can see, after inheriting uicollectionviewflowlayout, print the results of these cell frames in the-Layoutattributesforelementsinrect: Method
-(nsarray*) Layoutattributesforelementsinrect: (cgrect) rect{ nsmutablearray* attributes = [[Super Layoutattributesforelementsinrect:rect] mutablecopy]; For (uicollectionviewlayoutattributes *attr in attributes) { NSLog (@ "%@", Nsstringfromcgrect ([attr frame]);} }
As can be seen from the above two lines, my height is 42.8, but two cell X-value spacing is 46, that is, there is about 3px spacing.
In fact, as the name of Minimuminteritemspacing, this property is set to the minimum spacing, then we actually need to be a "maximuminteritemspacing", that is, the maximum spacing. To solve this problem, you need to do some calculations yourself.
Still inherit uicollectionviewflowlayout, then add the following code to the-Layoutattributesforelementsinrect: Method:
From the second loop to the last for (int i = 1; i < [attributes Count]; ++i) { //Current attributes Uicollectionviewlayoutattributes *currentlayoutattributes = attributes[i]; Previous attributes uicollectionviewlayoutattributes *prevlayoutattributes = attributes[i-1]; We want to set the maximum spacing, can be changed according to nsinteger maximumspacing = 0; The rightmost nsinteger of the previous cell is origin = Cgrectgetmaxx (prevlayoutattributes.frame); If the right side of the current cell plus the spacing we want plus the width of the current cell is still in contentsize, we change the current cell's origin position //No, the consequence of this judgment is that Uicollectionview only displays one row, The reason is that all of the cell x values below are appended to the last element of the first line if (Origin + maximumspacing + CurrentLayoutAttributes.frame.size.width < Self.collectionViewContentSize.width) { CGRect frame = currentlayoutattributes.frame; Frame.origin.x = Origin + maximumspacing; Currentlayoutattributes.frame = frame; } }
The reason note has been explained in great detail. This will solve the cell spacing problem. Run again, the effect is very good:
iOS development--Resolving uicollectionview cell spacing and setting mismatch issues