From ebfd614a04a578039516f06e3d38ec0ed9ba157a Mon Sep 17 00:00:00 2001 From: redth Date: Mon, 4 Dec 2023 19:55:12 -0500 Subject: [PATCH] Fix usage of weakref for cell tap callback --- .../Apple/CvCell.ios.maccatalyst.cs | 23 ++++++++++++++++--- .../Apple/CvDataSource.ios.maccatalyst.cs | 4 ++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/VirtualListView/Apple/CvCell.ios.maccatalyst.cs b/VirtualListView/Apple/CvCell.ios.maccatalyst.cs index 076f2cf..7e0eff3 100644 --- a/VirtualListView/Apple/CvCell.ios.maccatalyst.cs +++ b/VirtualListView/Apple/CvCell.ios.maccatalyst.cs @@ -23,7 +23,12 @@ public CvCell(CGRect frame) : base(frame) this.ContentView.AddGestureRecognizer(new UITapGestureRecognizer(() => InvokeTap())); } - public WeakReference> TapHandler { get; set; } + private TapHandlerCallback TapHandler; + + public void SetTapHandlerCallback(Action callback) + { + TapHandler = new TapHandlerCallback(callback); + } WeakReference keyCommands; @@ -57,8 +62,7 @@ void InvokeTap() { if (PositionInfo.Kind == PositionKind.Item) { - if (TapHandler?.TryGetTarget(out var handler) ?? false) - handler?.Invoke(this); + TapHandler.Invoke(this); } } @@ -142,4 +146,17 @@ public void UpdatePosition(PositionInfo positionInfo) viewPositionInfo.Update(positionInfo); } } + + class TapHandlerCallback + { + public TapHandlerCallback(Action callback) + { + Callback = callback; + } + + public readonly Action Callback; + + public void Invoke(CvCell cell) + => Callback?.Invoke(cell); + } } \ No newline at end of file diff --git a/VirtualListView/Apple/CvDataSource.ios.maccatalyst.cs b/VirtualListView/Apple/CvDataSource.ios.maccatalyst.cs index cf0873c..be6bf5a 100644 --- a/VirtualListView/Apple/CvDataSource.ios.maccatalyst.cs +++ b/VirtualListView/Apple/CvDataSource.ios.maccatalyst.cs @@ -39,8 +39,8 @@ public override UICollectionViewCell GetCell(UICollectionView collectionView, NS _ => "UNKNOWN", }; - var cell = collectionView.DequeueReusableCell(nativeReuseId, indexPath) as CvCell; - cell.TapHandler = new WeakReference>(TapCellHandler); + var cell = (collectionView.DequeueReusableCell(nativeReuseId, indexPath) as CvCell)!; + cell.SetTapHandlerCallback(TapCellHandler); cell.Handler = Handler; cell.IndexPath = new WeakReference(indexPath);