【发布时间】:2016-11-16 04:20:54
【问题描述】:
在启用分页的情况下,我一直在尝试使用 UICollectionView 将我的单元格居中对齐。不幸的是,在尝试执行此操作时,我永远无法使单元格在中心对齐。当我滚动浏览集合时,单元格总是会稍微偏离。我试图为纵向和横向视图实现这一点。我一直在使用插图来尝试将单元格及其位置居中:
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation)){
return UIEdgeInsetsMake(50.0,inset,0.0,inset); // top, left, bottom, right
}
else{
return UIEdgeInsetsMake(50.0,inset,0.0,inset); // top, left, bottom, right
}
}
然后我改变了行距:
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)
collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
CGFloat cellSpacing = ((UICollectionViewFlowLayout *) collectionViewLayout).minimumLineSpacing;
CGFloat cellWidth = ((UICollectionViewFlowLayout *) collectionViewLayout).itemSize.width;
NSInteger cellCount = [collectionView numberOfItemsInSection:section];
CGFloat inset = (collectionView.bounds.size.width - ((cellCount-1) * (cellWidth + cellSpacing))) * 0.5;
inset = MAX(inset, 0.0);
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
NSLog(@"Changed to landscape Spacing");
return inset;
}
else{
return inset;
}
我的单元格的大小在这里设置:
-(CGSize)
collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
//Set Landscape size of cells
if(UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation)){
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-360;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-60;
NSLog(@"Is Landscape");
return CGSizeMake(cellWidth, cellHeigt);
}
//Set Potrait size of cells
else{
CGFloat cellWidth = [[UIScreen mainScreen] bounds].size.width-60;
CGFloat cellHeigt = [[UIScreen mainScreen] bounds].size.height-160;
NSLog(@"Is Portrait");
return CGSizeMake(cellWidth, cellHeigt);
}
}
【问题讨论】:
-
您是否在属性检查器中为集合视图启用了分页?而不是使用像 360 或 60 这样的幻数,您应该使用与屏幕尺寸相关的值,即基于屏幕宽度/高度的划分(因为它可能在具有不同屏幕尺寸的设备上失败)。
-
是的,我使用了那些“神奇”的数字,这样我就可以得到合适的单元格大小。你会如何建议我获得最佳尺寸的细胞。至于分页,我通过集合委托启用了它。
coll.pagingEnabled = YES; -
好吧,我不确定您要达到什么目的,但不是尝试操纵单元格的内容视图(因为它留下了出错的空间),我只是将单元格设置为整个屏幕宽度,然后使用 autoLayout 将其内容居中。如果您可以发布您想要实现的目标的图片,也许我可以提供帮助!
-
是的,我知道我会尽快这样做
-
即使在这种情况下也要启用分页!由于分页可以让您的单元格完整显示! (并删除单元格之间的所有项目间间距)。让我知道它是否解决了您的问题,我会将其添加为答案!
标签: ios objective-c uicollectionview uicollectionviewcell