自定义属性中的UICollectionViewLayoutAttributes子类返回nil

13
我已经对UICollectionViewLayoutAttributes类进行了子类化,并添加了一些自定义属性。
在我的自定义UICollectionViewLayout类中,我覆盖了静态的+ (Class)layoutAttributesClass方法,并返回了我新的属性类。
在我的UICollectionViewLayout类中,我重写了-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect方法,并将值设置为自定义属性。
我可以在那里检查属性类,看到自定义属性被正确设置。
所以,最后我需要在UICollectionViewCell中检索这些属性,因此我重写了-(void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes方法来获取自定义UICollectionViewLayoutAttributes类中的值,但它们为空。就好像我从未设置过它们一样。
其他所有属性都正常工作,包括变换等。所以很明显,我做错了什么。请给予建议。
附上我的自定义类的HeaderFile。
@interface UICollectionViewLayoutAttributesWithColor : UICollectionViewLayoutAttributes

@property (strong,nonatomic) UIColor *color;

@end

这里是具体实现代码。如您所见,没有什么特别之处。

@implementation UICollectionViewLayoutAttributesWithColor

@synthesize color=_color;

@end

1
布局属性对象是否返回您自定义类的实例?您能否包含自定义类的实现? - jrturton
发布更新,包括类。 - Jason Cragun
我也遇到了这个问题。也许这是一个bug?文档中没有任何提示需要做其他的事情。 - griotspeak
3个回答

27

你会很高兴知道答案是简单的。你只需要重写copyWithZone:方法,因为UICollectionViewAttributes实现了NSCopying协议。问题在于苹果代码正在复制你的自定义属性对象,但由于你没有实现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;
}

哎呀...这真是个好发现。刚刚被这个问题给咬了一口。 - mattjgalloway

1
“删除自定义数值的问题,是因为我们必须实现-copyWithZone:方法,因为UICollectionViewLayoutAttributes类实现并使用了NSCopying。”

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;

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接