Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewLayoutAttributes Subclass returning nil in custom properties

Tags:

ios

iphone

ios6

I have subclassed the UICollectionViewLayoutAttributes class and added a few custom properties.

In my custom UICollectionViewLayout class, I am overriding the static + (Class)layoutAttributesClass and I return my new attributes class.

In my UICollectionViewLayout class I override the -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect and I set the values to the custom properties.

I can inspect the attributes class right there and see that the custom properties are set properly.

So, lastly I need to retrieve these properties in the UICollectionViewCell, so I override the -(void) applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes to fetch the values in the custom UICollectionViewLayoutAttributes class, YET they are nil. As if I never set them.

All the rest of the attributes are working perfectly, including transforms and such. So clearly, Im doing something wrong. Please advise.

Included is the HeaderFile of my custom class

@interface UICollectionViewLayoutAttributesWithColor : UICollectionViewLayoutAttributes

@property (strong,nonatomic) UIColor *color;

@end

and here is the implementation. As you can see, nothing special

@implementation UICollectionViewLayoutAttributesWithColor

@synthesize color=_color;

@end
like image 302
Jason Cragun Avatar asked Oct 05 '12 02:10

Jason Cragun


2 Answers

you will be glad to know the answer is simple. You just need to override copyWithZone: as the UICollectionViewAttributes implements the NSCopying protocol. What's happening is Apple code is making copies of your custom attributes object, but because you haven't implemented copyWithZone, your custom attributes are not being copied to the new object. Here's an example of what you need to do:

@interface IRTableCollectionViewLayoutAttributes : UICollectionViewLayoutAttributes {
    CGRect _textFieldFrame;
}

@property (nonatomic, assign) CGRect  textFieldFrame;

@end

and the implementation:

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

    return newAttributes;
}
like image 65
TheBasicMind Avatar answered Oct 18 '22 17:10

TheBasicMind


The issue of dropping custom values is because we have to implement -copyWithZone: because UICollectionViewLayoutAttributes implements and uses NSCopying

like image 1
griotspeak Avatar answered Oct 18 '22 16:10

griotspeak