Search code examples
xamarinxamarin.iosuicollectionviewlayout

UICollectionViewLayoutAttributes custom derived class instance is not created


I have created this class

public class CustomLayoutAttributes: UICollectionViewLayoutAttributes
    {
        public float PhotoHeight { get; set; }

        public override NSObject Copy (NSZone zone)
        {
            CustomLayoutAttributes copy = base.Copy(zone) as CustomLayoutAttributes;
            copy.PhotoHeight = PhotoHeight;
            return copy;
        }

        public override bool IsEqual (NSObject anObject)
        {
            CustomLayoutAttributes attributes = anObject as CustomLayoutAttributes;
            if (attributes != null) {
                if (attributes.PhotoHeight == PhotoHeight) {
                    return base.IsEqual (anObject);
                }
            }
            return false;
        }

        public CustomLayoutAttributes (IntPtr ptr) : base(ptr)
        {

        }
    }

And in my CustomCollectionViewLayout PrepareLayout method I try to create an instance but always get null.

    [Register("CustomCollectionViewLayout")]
    public class CustomCollectionViewLayout : UICollectionViewLayout
    {   
        public override void PrepareLayout ()
        {
        // stuff... 
                CustomLayoutAttributes attributes = CustomLayoutAttributes.CreateForCell(indexPath) as CustomLayoutAttributes;
                if (attributes != null) {
                    // Never gets in here, always null
                }
        // stuff...
        }
    }

I have applied the same login in Swift iOS and it works perfect.


Solution

  • Need to use the generic version of CreateForCell:

    UICollectionViewLayout.CreateForCell<CustomLayoutAttributes>(indexPath);
    

    This is because C# doesn't have virtual class methods like Objective-C does so it can't tell in CreateForCell which class you called it on unless you tell it with a type argument.