【问题标题】:Display CollectionViewCell in starting position在起始位置显示 CollectionViewCell
【发布时间】:2020-02-25 09:08:36
【问题描述】:

我使用 Xib 文件创建了一个集合视图单元格。而且我只有一个单元格,但该单元格显示在 collectionView 的中心。我想在 collectionView 的起始位置显示单元格。

我在 viewDidLoad 中修复了 contentInset 并在此处加载单元格 xib 文件,

_listCollectionView.contentInset = UIEdgeInsetsMake(0 , 0, 0, 0);  

我的单元格大小是

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {


    return  CGSizeMake(156,140);
}

像这样显示的单元格。

【问题讨论】:

  • 你能添加一个附件吗
  • @呃。 Khatri,我附上了图片,请检查一下。
  • 默认情况下,collectionView 对齐是居中的,因此如果您只有单个单元格,请尝试在视图上相应地对齐 collectionView。 (与单元格相同大小的集合视图)并与视图左侧对齐
  • @Pravin Tate,热心修复它。
  • @ios 正如 Pravin 所说,您将宽度和高度集合视图更改为单元格宽度和高度。您可以通过编程方式实现这一点。如果您使用自动布局,则将出口连接指定为宽度和高度并更改其值。另一种方式,您可以使用瀑布模式进行集合视图流布局。有许多框架作品可用于此。你可以使用它们。

标签: ios objective-c xcode uicollectionview uicollectionviewcell


【解决方案1】:

collectionView: cellForItemAtIndexPath: 函数中,我进行了这样的更改。

这里只是我在加载单元格后将我的 collectionviewcell x 原点位置固定为 0

deviceCell= (DeviceCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"DeviceCollectionViewCell" forIndexPath:indexPath];

if (listArray.count == 1) {//Here i fixed the my cell x origin position
    CGRect frameRect = deviceCell.frame;//Copy cell frame
     frameRect.origin.x = 0;//Set cell origin.x
     deviceCell.frame = frameRect;//Reset frame
}

【讨论】:

    【解决方案2】:

    我对您的问题不是很清楚,但我认为您所指的是将 collectionnView 元素与视图对齐。您必须使用UICollectionViewLayoutAttributeslayoutAttributesforElements 来实现这一点。看看下面的代码,如果你想在 Objective c 中做。

    -(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
        CGFloat leftMargin = self.sectionInset.left; //initalized to silence compiler, and actaully safer, but not planning to use.
        CGFloat maxY = -1.0f;
    
        //this loop assumes attributes are in IndexPath order
    
        for (UICollectionViewLayoutAttributes *attribute in attributes) {
        if (attribute.frame.origin.y >= maxY) {
            leftMargin = self.sectionInset.left;
        }
    
    
         attribute.frame = CGRectMake(leftMargin, attribute.frame.origin.y, 
         attribute.frame.size.width, attribute.frame.size.height);
    
         leftMargin += attribute.frame.size.width + self.minimumInteritemSpacing;
         maxY = MAX(CGRectGetMaxY(attribute.frame), maxY);
        }
    
         return attributes;
    
        }
    

    【讨论】:

    • 看我的回答。这很简单,对我有用...非常感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多