UICollectionViewFlowLayout 很棒,但是,我希望它稍微调整一下,以便 scrollDirection 与布局方向不同。我想要的示例是跳板主屏幕或表情符号键盘,您可以在其中向左/向右滑动,但单元格从左到右、从上到下排列(而不是从上到下、从左到右,因为它们是UICollectionViewFlowLayout 与 scrollDirection 设置为水平)。任何人都知道我可以如何轻松地对 FlowLayout 进行子类化以进行此更改?我很失望他们在 UICollectionViewFlowLayout 对象上除了 scrollDirection 之外没有 layoutDirection :(
@rdelmar 我实现了与您的解决方案类似的东西,并且有效(不像我想要的那样优雅),但我注意到偶尔项目会从集合中消失,除非重新绘制,这就是我不接受答案的原因。这是我最终得到的结果:
@interface UICollectionViewPagedFlowLayout : UICollectionViewFlowLayout
@property int width;
@property int height;
@end
@implementation UICollectionViewPagedFlowLayout
#warning MINOR BUG: sometimes symbols disappear
- (CGSize)collectionViewContentSize {
CGSize size = [super collectionViewContentSize];
// make sure it's wide enough to cover all the objects
size.width = self.collectionView.bounds.size.width * [self.collectionView numberOfSections];
return size;
}
- (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)) {
// see which section this is in
CGRect configurableRect = UIEdgeInsetsInsetRect(visibleRect, self.sectionInset);
int horizontalIndex = attributes.indexPath.row % self.width;
int verticalIndex = attributes.indexPath.row / self.width;
double xspace = (configurableRect.size.width - self.width * self.itemSize.width) / self.width;
double yspace = (configurableRect.size.height - self.height * self.itemSize.height) / self.height;
attributes.center = CGPointMake(attributes.indexPath.section * visibleRect.size.width + self.sectionInset.left + (self.itemSize.width + xspace) * horizontalIndex + self.itemSize.width / 2, self.sectionInset.top + (self.itemSize.height + yspace) * verticalIndex + self.itemSize.height / 2);
}
}
return array;
}
@end