Skip to content

Commit

Permalink
Fix usage of weakref for cell tap callback
Browse files Browse the repository at this point in the history
  • Loading branch information
Redth committed Dec 5, 2023
1 parent 6ec23c3 commit ebfd614
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
23 changes: 20 additions & 3 deletions VirtualListView/Apple/CvCell.ios.maccatalyst.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,12 @@ public CvCell(CGRect frame) : base(frame)
this.ContentView.AddGestureRecognizer(new UITapGestureRecognizer(() => InvokeTap()));
}

public WeakReference<Action<CvCell>> TapHandler { get; set; }
private TapHandlerCallback TapHandler;

public void SetTapHandlerCallback(Action<CvCell> callback)
{
TapHandler = new TapHandlerCallback(callback);
}

WeakReference<UIKeyCommand[]> keyCommands;

Expand Down Expand Up @@ -57,8 +62,7 @@ void InvokeTap()
{
if (PositionInfo.Kind == PositionKind.Item)
{
if (TapHandler?.TryGetTarget(out var handler) ?? false)
handler?.Invoke(this);
TapHandler.Invoke(this);
}
}

Expand Down Expand Up @@ -142,4 +146,17 @@ public void UpdatePosition(PositionInfo positionInfo)
viewPositionInfo.Update(positionInfo);
}
}

class TapHandlerCallback
{
public TapHandlerCallback(Action<CvCell> callback)
{
Callback = callback;
}

public readonly Action<CvCell> Callback;

public void Invoke(CvCell cell)
=> Callback?.Invoke(cell);
}
}
4 changes: 2 additions & 2 deletions VirtualListView/Apple/CvDataSource.ios.maccatalyst.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ public override UICollectionViewCell GetCell(UICollectionView collectionView, NS
_ => "UNKNOWN",
};

var cell = collectionView.DequeueReusableCell(nativeReuseId, indexPath) as CvCell;
cell.TapHandler = new WeakReference<Action<CvCell>>(TapCellHandler);
var cell = (collectionView.DequeueReusableCell(nativeReuseId, indexPath) as CvCell)!;
cell.SetTapHandlerCallback(TapCellHandler);
cell.Handler = Handler;
cell.IndexPath = new WeakReference<NSIndexPath>(indexPath);

Expand Down

0 comments on commit ebfd614

Please sign in to comment.