13

我对 UICollectionViewLayoutAttributes 类进行了子类化并添加了一些自定义属性。

在我的自定义 UICollectionViewLayout 类中,我将覆盖静态 + (Class)layoutAttributesClass 并返回我的新属性类。

在我的 UICollectionViewLayout 类中,我覆盖了-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect并将值设置为自定义属性。

我可以在那里检查属性类,并查看自定义属性是否设置正确。

所以,最后我需要在 UICollectionViewCell 中检索这些属性,所以我重写-(void) applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes以获取自定义 UICollectionViewLayoutAttributes 类中的值,但它们是 nil。好像我从来没有设置它们一样。

所有其他属性都可以正常工作,包括转换等。很明显,我做错了什么。请指教。

包括我的自定义类的 HeaderFile

@interface UICollectionViewLayoutAttributesWithColor : UICollectionViewLayoutAttributes

@property (strong,nonatomic) UIColor *color;

@end

这是实现。如您所见,没有什么特别的

@implementation UICollectionViewLayoutAttributesWithColor

@synthesize color=_color;

@end
4

3 回答 3

27

你会很高兴知道答案很简单。您只需要覆盖 copyWithZone: 因为 UICollectionViewAttributes 实现了 NSCopying 协议。发生的事情是 Apple 代码正在复制您的自定义属性对象,但由于您尚未实现 copyWithZone,因此您的自定义属性不会被复制到新对象。这是您需要执行的操作的示例:

@interface IRTableCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes {
    CGRect _textFieldFrame;
}

@property (nonatomic, assign) CGRect  textFieldFrame;

@end

和实施:

- (id)copyWithZone:(NSZone *)zone
{
    IRTableCollectionViewLayoutAttributes *newAttributes = [super copyWithZone:zone];
    newAttributes->_textFieldFrame = _textFieldFrame;

    return newAttributes;
}
于 2012-10-18T17:59:52.310 回答
1

删除自定义值的问题是因为我们必须实现 -copyWithZone: 因为 UICollectionViewLayoutAttributes 实现并使用 NSCopying

于 2012-10-18T18:11:27.960 回答
0

听起来您正在尝试将布局属性应用于单元格。可以这样做:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //Get Cell
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];

    //Apply Attributes
    UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    [cell applyLayoutAttributes:attributes];

    return cell;
}

但是,在我的 UICollectionView 实现中,我只是将自定义属性添加到我的 UICollectionViewCell 子类而不是 UICollectionViewLayoutAttributes 子类中。我认为在大多数情况下子类化 UICollectionViewCell 更有效:

@interface ColoredCollectionCell : UICollectionViewCell
@property (strong,nonatomic) UIColor *color;
@end

@implementation ColoredCollectionCell
// No need to @synthesize in iOS6 sdk
@end

在您的集合视图控制器中:

- (UICollectionViewCell*)collectionView:(UICollectionView*)cv cellForItemAtIndexPath:(NSIndexPath*)indexPath
{
    //Get the Cell
    ColoredCollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"MY_CELL" forIndexPath:indexPath];

    //Get the color from Array of colors
    UIColor *thisColor = self.colorsArray[indexPath.item];

    //Set cell color
    cell.color = thisColor;

    return cell;

}
于 2012-10-10T02:04:24.783 回答