You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

F# Xamarin重写UICollectionViewFlowLayout的GetSizeForItem方法报错

问题分析与解决方案:UICollectionViewCell尺寸设置报错

问题根源

你这里犯了一个典型的角色混淆错误:

  • UICollectionViewFlowLayout 是负责管理布局规则的布局类,但它本身并没有GetSizeForItem这个方法
  • collectionView:layout:sizeForItemAtIndexPath: 这个方法属于UICollectionViewDelegateFlowLayout协议,需要由集合视图的代理对象来实现,而不是继承布局类去重写

你错误地继承了UICollectionViewFlowLayout来重写一个不存在的方法,这就是运行时报错的核心原因。

正确的F#实现代码

你需要创建一个实现UICollectionViewDelegateFlowLayout协议的代理类,或者让你的视图控制器直接承担代理职责。下面是完整的示例代码:

// 实现UICollectionViewDelegateFlowLayout的代理类
type CollectionViewFlowDelegate(handle: IntPtr) as this =
    inherit UICollectionViewDelegateFlowLayout(handle)
    
    // 重写GetSizeForItem方法,为每个Cell指定尺寸
    override this.GetSizeForItem(collectionView: UICollectionView, layout: UICollectionViewLayout, indexPath: NSIndexPath) =
        CGSize(100.0, 300.0)

// 在视图控制器中完成集合视图的初始化与配置
type YourViewController() as this =
    inherit UIViewController()
    let mutable collectionView: UICollectionView = null
    
    override this.ViewDidLoad() =
        base.ViewDidLoad()
        
        // 创建流式布局实例
        let flowLayout = UICollectionViewFlowLayout()
        // 可选:设置全局默认Item尺寸(当代理方法未返回时会 fallback 到这个值)
        flowLayout.ItemSize <- CGSize(80.0, 200.0)
        
        // 初始化集合视图
        collectionView <- UICollectionView(
            frame = CGRect(0.0, 0.0, this.View.Bounds.Width, this.View.Bounds.Height),
            layout = flowLayout
        )
        // 设置代理为我们刚才创建的FlowDelegate
        collectionView.Delegate <- CollectionViewFlowDelegate(IntPtr.Zero)
        
        // 注册Cell、设置数据源等其他必要操作...
        this.View.AddSubview(collectionView)

额外补充说明

  1. 如果你的视图控制器本身想作为代理,可以让它直接实现UICollectionViewDelegateFlowLayout接口,或者继承UICollectionViewController(后者默认集成了相关代理能力)
  2. UICollectionViewFlowLayout的ItemSize属性是全局默认值,而代理方法GetSizeForItem支持针对不同IndexPath返回差异化尺寸,优先级高于全局默认值
  3. 要注意代理对象的生命周期,确保它和集合视图的生命周期保持一致,避免被提前回收导致代理失效

内容的提问来源于stack exchange,提问作者Alk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:43:17