未创建 UICollectionViewLayoutAttributes 自定义派生 class 实例

UICollectionViewLayoutAttributes custom derived class instance is not created

我创建了这个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)
        {

        }
    }

在我的 CustomCollectionViewLayout PrepareLayout 方法中,我尝试创建一个实例,但总是得到 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...
        }
    }

我在 Swift iOS 中应用了相同的登录名,并且效果很好。

需要使用generic version of CreateForCell:

UICollectionViewLayout.CreateForCell<CustomLayoutAttributes>(indexPath);

这是因为 C# 没有像 Objective-C 这样的虚拟 class 方法,所以它无法在 CreateForCell 中告诉你调用了哪个 class 除非你告诉它类型参数。