设置 UICollectionViewDelegateFlowLayout Xamarin iOS F#

Setting UICollectionViewDelegateFlowLayout Xamarin iOS F#

我创建了一个 UICollectionViewDelegateFlowLayout 的实例,如下所示:

type CollectionViewFlowDelegate (handle:IntPtr) = 
    inherit UICollectionViewDelegateFlowLayout (handle)

    override x.GetSizeForItem(collectionView : UICollectionView, layout : UICollectionViewLayout, indexPath : NSIndexPath) =
        CGSize(100.0, 300.0)

我还有一个UICollectionViewController定义如下:

[<Register ("LandlordHome")>]
type LandlordHome (handle:IntPtr)  =
    inherit UICollectionViewController (handle)

    let addToList (listan:List<Listing>) (element:Listing) = element::listan

let mutable listings : List<Listing> = List.Empty

override x.ViewDidLoad () =
    base.ViewDidLoad ()
    x.View.BackgroundColor <- UIColor.Gray
    for i in 1..10 do
        let listing : Listing = new Listing(....code....)
        listings <- listing::listings
    x.CollectionView.BackgroundColor <- UIColor.Green
    //x.CollectionView.Delegate <- new CollectionViewFlowDelegate(handle);
    x.CollectionView.RegisterClassForCell(typeof<ChatViewCell>, new NSString("ChatCell")) 


override x.ViewDidAppear(animated) = 
    x.CollectionView.ReloadData()

override x.NumberOfSections(collectionView : UICollectionView) = 
     Conversions.nint(1)

override x.GetItemsCount(collectionView : UICollectionView, section : nint) =
     Conversions.nint(listings.Length)

这很好用。但是,现在我想在 UICollectionViewController 中为 collectionView 设置委托,以便 UICollectionViewCell 的大小被覆盖。为此,我取消注释此行:

 //x.CollectionView.Delegate <- new CollectionViewFlowDelegate(handle);

这会导致程序在此处崩溃:

Conversions.nint(listings.Length)

但有以下例外:

System.NullReferenceException has been thrown. Object reference not set to an instance of an object.

这对我来说没有任何意义,因为代码在没有设置委托的情况下工作正常,所以 listings 不为空。

恐怕你忘了使用 Register 属性。

[<Register ("CollectionViewFlowDelegate")>]
type CollectionViewFlowDelegate (handle:IntPtr) = 
inherit UICollectionViewDelegateFlowLayout (handle)