ios UICollectionView 中的单元格间距
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17229350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cell spacing in UICollectionView
提问by Vishal Singh
How do I set cell spacing in a section of UICollectionView
? I know there is a property minimumInteritemSpacing
I have set it to 5.0 still the spacing is not appearing 5.0. I have implemented the flowout delegate method.
如何在 的一部分中设置单元格间距UICollectionView
?我知道有一个属性minimumInteritemSpacing
我已将其设置为 5.0,但间距并未出现 5.0。我已经实现了流出委托方法。
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return 5.0;
}
still I am not getting the desired result. I think its the minimum spacing . Isn't there any way by which I can set the maximum spacing?
我仍然没有得到想要的结果。我认为它的最小间距。有没有什么办法可以设置最大间距?
采纳答案by iago849
I know that the topic is old, but in case anyone still needs correct answer here what you need:
我知道这个话题很旧,但如果有人仍然需要正确的答案,你需要什么:
- Override standard flow layout.
Add implementation like that:
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect { NSArray *answer = [super layoutAttributesForElementsInRect:rect]; for(int i = 1; i < [answer count]; ++i) { UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i]; UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1]; NSInteger maximumSpacing = 4; NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame); if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) { CGRect frame = currentLayoutAttributes.frame; frame.origin.x = origin + maximumSpacing; currentLayoutAttributes.frame = frame; } } return answer; }
- 覆盖标准流布局。
添加这样的实现:
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect { NSArray *answer = [super layoutAttributesForElementsInRect:rect]; for(int i = 1; i < [answer count]; ++i) { UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i]; UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1]; NSInteger maximumSpacing = 4; NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame); if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) { CGRect frame = currentLayoutAttributes.frame; frame.origin.x = origin + maximumSpacing; currentLayoutAttributes.frame = frame; } } return answer; }
where maximumSpacing could be set to any value you prefer. This trick guarantees that the space between cells would be EXACTLY equal to maximumSpacing!!
其中 maximumSpacing 可以设置为您喜欢的任何值。这个技巧保证单元格之间的空间将完全等于maximumSpacing!!
回答by jerik
Supporting the initial question. I tried to get the spacing to 5px on the UICollectionView
but this does not work, as well with a UIEdgeInsetsMake(0,0,0,0)
...
支持最初的问题。我试图将间距设置为 5pxUICollectionView
但这不起作用,以及UIEdgeInsetsMake(0,0,0,0)
...
On a UITableView I can do this by directly specifying the x,y coordinates in a row...
在 UITableView 上,我可以通过直接指定一行中的 x,y 坐标来做到这一点...
Heres my UICollectionView code:
这是我的 UICollectionView 代码:
#pragma mark collection view cell layout / size
- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
return [self getCellSize:indexPath]; // will be w120xh100 or w190x100
// if the width is higher, only one image will be shown in a line
}
#pragma mark collection view cell paddings
- (UIEdgeInsets)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
return UIEdgeInsetsMake(0, 0, 0, 0); // top, left, bottom, right
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 5.0;
}
Update: Solved my problem, with the following code.
更新:使用以下代码解决了我的问题。
ViewController.m
视图控制器.m
#import "ViewController.h"
#import "MagazineCell.h" // created just the default class.
static NSString * const cellID = @"cellID";
@interface ViewController ()
@end
@implementation ViewController
#pragma mark - Collection view
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 30;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
MagazineCell *mCell = (MagazineCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
mCell.backgroundColor = [UIColor lightGrayColor];
return mCell;
}
#pragma mark Collection view layout things
// Layout: Set cell size
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"SETTING SIZE FOR ITEM AT INDEX %d", indexPath.row);
CGSize mElementSize = CGSizeMake(104, 104);
return mElementSize;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
return 2.0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
return 2.0;
}
// Layout: Set Edges
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
// return UIEdgeInsetsMake(0,8,0,8); // top, left, bottom, right
return UIEdgeInsetsMake(0,0,0,0); // top, left, bottom, right
}
@end
回答by Jason Moore
Using a horizontal flow layout, I was also getting a 10 points spacing between cells. To remove the spacing I needed to set minimumLineSpacing
as well as minimumInterItemSpacing
to zero.
使用水平流布局,我还得到了单元格之间的 10 点间距。要删除我需要设置的间距minimumLineSpacing
以及minimumInterItemSpacing
为零。
UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
flow.itemSize = CGSizeMake(cellWidth, cellHeight);
flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
flow.minimumInteritemSpacing = 0;
flow.minimumLineSpacing = 0;
Also, if all your cells are the same size, it's simpler and more efficient to set the property on the flow layout directly instead of using delegate methods.
此外,如果所有单元格的大小相同,则直接在流布局上设置属性而不是使用委托方法更简单、更有效。
回答by Vincent Joy
Remember, it is minimum line space, not minimum inter item spacing or cell space. Because your collectionView's scroll direction is HORIZONTAL.
请记住,它是最小行间距,而不是最小项目间距或单元格间距。因为您的 collectionView 的滚动方向是HORIZONTAL。
If it is vertical then you need to set cell space or inter item space for horizontal space between cells and line spacing for vertical space between cells.
如果它是垂直的,那么您需要为单元格之间的水平空间设置单元格空间或项目间空间,为单元格之间的垂直空间设置行距。
Objective-C version
Objective-C 版本
- (CGFloat)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout*)collectionViewLayout
minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return 20;
}
Swift version:
迅捷版:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 20
}
回答by LASoft
Try this code to ensure you have a spacing of 5px between each item:
试试这个代码以确保每个项目之间有 5px 的间距:
- (UIEdgeInsets)collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout *) collectionViewLayout
insetForSectionAtIndex:(NSInteger) section {
return UIEdgeInsetsMake(0, 0, 0, 5); // top, left, bottom, right
}
- (CGFloat)collectionView:(UICollectionView *) collectionView
layout:(UICollectionViewLayout *) collectionViewLayout
minimumInteritemSpacingForSectionAtIndex:(NSInteger) section {
return 5.0;
}
回答by Vojtech Vrbka
Swiftversion of the most popular answer. Space between the cells will be equal to cellSpacing
.
最受欢迎答案的Swift版本。单元格之间的空间将等于cellSpacing
。
class CustomViewFlowLayout : UICollectionViewFlowLayout {
let cellSpacing:CGFloat = 4
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
if let attributes = super.layoutAttributesForElementsInRect(rect) {
for (index, attribute) in attributes.enumerate() {
if index == 0 { continue }
let prevLayoutAttributes = attributes[index - 1]
let origin = CGRectGetMaxX(prevLayoutAttributes.frame)
if(origin + cellSpacing + attribute.frame.size.width < self.collectionViewContentSize().width) {
attribute.frame.origin.x = origin + cellSpacing
}
}
return attributes
}
return nil
}
}
回答by Aamir
I have found very easy way to configure spacing between cells or rows by using IB.
我发现使用 IB 配置单元格或行之间的间距非常简单。
Just select UICollectionView from storyboard/Xib file and click in Size Inspectoras specified in below image.
只需从故事板/Xib 文件中选择 UICollectionView 并单击下图指定的大小检查器。
For configuring space programatically use following properties.
要以编程方式配置空间,请使用以下属性。
1) For setting space between rows.
1) 用于设置行之间的空间。
[self.collectionView setMinimumLineSpacing:5];
2) For setting space between items/cells.
2) 用于设置项目/单元格之间的空间。
[self.collectionView setMinimumInteritemSpacing:5];
回答by Anil Varghese
Please note the property name minimumInterItemSpacing. This will be the minimum spacingbetween the items not the exactspacing. If you set minimumInterItemSpacing to some value you can assure that spacing wont be a value less than that. But there is a chance get a higher value.
请注意属性名称minimumInterItemSpacing。这将是项目之间的最小间距,而不是精确间距。如果将 minimumInterItemSpacing 设置为某个值,则可以确保间距不会小于该值。但有机会获得更高的价值。
Actually the spacing between items depends on several factors itemSizeand sectionInset. Collection view dynamically place the contents based on these values. So you cannot assure the exact spacing. You should do some trial and error with sectionInsetand minimumInterItemSpacing.
实际上,项目之间的间距取决于几个因素itemSize和sectionInset。集合视图根据这些值动态放置内容。所以你不能保证准确的间距。您应该对sectionInset和minimumInterItemSpacing进行一些反复试验。
回答by Vadim Bulavin
Answer for Swift 3.0, Xcode 8
Swift 3.0、Xcode 8 的答案
1.Make sure you set collection view delegate
1.确保您设置了集合视图委托
class DashboardViewController: UIViewController {
@IBOutlet weak var dashboardCollectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
dashboardCollectionView.delegate = self
}
}
2.Implement UICollectionViewDelegateFlowLayoutprotocol, not UICollectionViewDelegate.
2.实现UICollectionViewDelegateFlowLayout协议,而不是 UICollectionViewDelegate。
extension DashboardViewController: UICollectionViewDelegateFlowLayout {
fileprivate var sectionInsets: UIEdgeInsets {
return .zero
}
fileprivate var itemsPerRow: CGFloat {
return 2
}
fileprivate var interitemSpace: CGFloat {
return 5.0
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let sectionPadding = sectionInsets.left * (itemsPerRow + 1)
let interitemPadding = max(0.0, itemsPerRow - 1) * interitemSpace
let availableWidth = collectionView.bounds.width - sectionPadding - interitemPadding
let widthPerItem = availableWidth / itemsPerRow
return CGSize(width: widthPerItem, height: widthPerItem)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return sectionInsets
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return interitemSpace
}
}
回答by AMayes
Simple code for spacing
间距的简单代码
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.minimumInteritemSpacing = 10 // Some float value