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
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;
}
The issue of dropping custom values is because we have to implement -copyWithZone: because UICollectionViewLayoutAttributes implements and uses NSCopying
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With