ios – 对UICollectionViewLayout进行子类化并分配给UICollectionView

我有一个CollectionViewController
- (void)viewDidLoad 
{
   [super viewDidLoad];    
   // assign layout (subclassed below)
   self.collectionView.collectionViewLayout = [[CustomCollectionLayout alloc] init];
}

// data source is working,here's what matters:
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   Thumbcell *cell = (Thumbcell *)[cv dequeueReusableCellWithReuseIdentifier:@"Thumbcell" forIndexPath:indexPath];

   return cell;
}

我还有一个UICollectionViewLayout子类:CustomCollectionLayout.m

#pragma mark - Overriden methods
- (CGSize)collectionViewContentSize
{
    return CGSizeMake(320,480);
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return [[super layoutAttributesForElementsInRect:rect] mutablecopy];
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // configure CellAttributes
    cellAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];

    // random position
    int xRand = arc4random() % 320;
    int yRand = arc4random() % 460;
    cellAttributes.frame = CGRectMake(xRand,yRand,150,170);

    return cellAttributes;
}

我正在尝试为单元格使用新框架,只是在随机位置使用一个框架.
问题是没有调用layoutAttributesForItemAtIndexPath.

提前感谢任何建议.

解决方法

编辑:我没有注意到你已经解决了你的情况,但我遇到了同样的问题,这就是我的情况.我将它留在这里,对于那些已经没有太多关于这个主题的人来说它可能是有用的.

在绘制时,UICollectionView不会调用方法layoutAttributesForItemAtIndexPath:但layoutAttributesForElementsInRect:以确定哪些单元格应该可见.您有责任实现此方法,并从那里调用layoutAttributesForItemAtIndexPath:用于所有可见索引路径以确定确切位置.

换句话说,将其添加到您的布局:

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:16];
    // Determine visible index paths
    for(???) {
        [array addobject:[self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:??? inSection:???]]];
    }
    return [array copy];
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...