如何使用UICollectionViewFlowLayout将UICollectionView中的所有单元格垂直和水平居中
Flow layout根据滚动方向将间距保留在右侧或底部。我想在所有的边上设置相同的填充。我已经使用了UICollectionViewFlowLayout的sectionInset属性。
发布于 2013-03-12 19:32:11
我建议实现UICollectionViewDelegateFlowLayout协议来动态实现单元格的水平和垂直居中。来自UICollectionViewDelegateFlowLayout协议参考
UICollectionViewDelegateFlowLayout协议定义了一些方法,使您可以与UICollectionViewFlowLayout对象协作来实现基于网格的布局。此协议的方法定义网格中项目的大小和项目之间的间距。
此协议中的所有方法都是可选的。如果未实现特定方法,流布局委托将使用其自身属性中的值来获取适当的间距信息。
流布局对象期望集合视图的委托对象采用此协议。因此,在分配给集合视图的委托属性的对象上实现此协议。
您最感兴趣的可能是collectionView:layout:insetForSectionAtIndex:方法,该方法可用于使用诸如UIEdgeInsetsMake之类的东西来调整屏幕四边的插图。您可以根据屏幕尺寸确定插入,方法是从相应的屏幕尺寸(垂直或水平)中减去适当的量,如单元格的大小。然后,除以2,得到特定维度的相等插入值。
发布于 2013-03-12 15:51:21
使用的区段插入?
好的,尝试使用minimumLineSpacing属性和minimumInteritemSpacing属性
minimumLineSpacing
对于垂直滚动网格,此行间距表示连续行之间的最小间距。对于水平滚动网格,此值表示连续列之间的最小间距。此间距不适用于页眉与第一行之间或最后一行与页脚之间的间距。
minimumInteritemSpacing
对于垂直滚动网格,此间距表示同一行中项目之间的最小间距。对于水平滚动网格,此值表示同一列中项目之间的最小间距。此间距用于计算一行中可以容纳多少项,但在确定项的数量后,实际间距可能会向上调整。
发布于 2013-03-12 23:16:57
创建UICollectionViewFlowLayout的子类并重写layoutAttributesForElementsInRect:方法以对齐UICollectionViewCells
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray* array = [super layoutAttributesForElementsInRect:rect];
CGRect visibleRect;
visibleRect.origin = self.collectionView.contentOffset;
visibleRect.size = self.collectionView.bounds.size;
for(UICollectionViewLayoutAttributes* attributes in array) {
if(CGRectIntersectsRect(attributes.frame, rect)){
CGFloat d = UIInterfaceOrientationIsPortrait(_orientation)?
CGRectGetMidY(visibleRect)-attributes.center.y :
CGRectGetMidX(visibleRect)-attributes.center.x;
CGFloat w = visibleRect.size.width;
CGFloat h = visibleRect.size.height;
CGFloat dRatio = UIInterfaceOrientationIsPortrait(_orientation)? d/(h/2) : d/(w/2);
CGFloat angle = MAX_ANGLE*dRatio; // an angle between 0 and MAX_ANGLE based on proximity to center
CGFloat radians = DEGREES_TO_RADIANS(angle);
debug = 0;
CATransform3D rotationAndPerspectiveTransform = CATransform3DIdentity;
rotationAndPerspectiveTransform.m34 = PERSPECTIVE;
rotationAndPerspectiveTransform = UIInterfaceOrientationIsPortrait(_orientation)?
CATransform3DRotate(rotationAndPerspectiveTransform, radians, 1.0f, 0.0f, 0.0f) :
CATransform3DRotate(rotationAndPerspectiveTransform, radians, 0.0f, 1.0f, 0.0f);
attributes.transform3D = rotationAndPerspectiveTransform;
}
}
return array;
}我没有为你编辑这段代码,而且有对宏和实例变量的引用,所以你需要调整它来做你想做的事情。这是用来创建一个覆盖流风格的布局,但原则将是相同的,但没有3D业务。您需要设置段插入,以保证流中只有一行或一列。
https://stackoverflow.com/questions/15355820
复制相似问题