Xamarin.iOS中如何通过长按TableView单元格读取数据?
解决TableView长按单元格获取数据的问题
你的核心问题是长按手势未关联对应单元格的数据源,以下两种方案可直接解决:
方案一:通过手势Tag绑定行索引
修改GetCell方法的手势创建逻辑,将当前行索引绑定到手势的Tag属性,后续在长按回调中通过Tag获取对应数据:
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { var cell = (TableClass)tableView.DequeueReusableCell("cell_id", indexPath); var AbsentDay = absentList[indexPath.Row]; // 移除cell上已有的长按手势,避免复用重复添加 foreach (var gesture in cell.GestureRecognizers?.Where(g => g is UILongPressGestureRecognizer) ?? Enumerable.Empty<UIGestureRecognizer>()) { cell.RemoveGestureRecognizer(gesture); } var longPressGesture = new UILongPressGestureRecognizer(LongPressMethod); // 将行索引绑定到Tag longPressGesture.Tag = indexPath.Row; cell.AddGestureRecognizer(longPressGesture); cell.UpdateCell(AbsentDay); return cell; } void LongPressMethod(UILongPressGestureRecognizer gestureRecognizer) { if (gestureRecognizer.State == UIGestureRecognizerState.Began) { int rowIndex = (int)gestureRecognizer.Tag; if (rowIndex >= 0 && rowIndex < absentList.Count) { var targetData = absentList[rowIndex]; Toast.MakeToast($"获取到数据:{targetData.BandValue}") .SetTitle(targetData.ToString()) .SetDuration(ToastDuration.Regular) .Show(); } } }
方案二:通过手势View获取单元格与索引
无需绑定Tag,直接通过手势关联的View找到单元格,再获取对应的NSIndexPath:
首先在适配器类中添加UITableView的引用(初始化时传入):
internal class AbsetAdapterClass : UITableViewSource { private List<benood2.AbsentClass> absentList; private UITableView _tableView; public AbsetAdapterClass(List<benood2.AbsentClass> absentList, UITableView tableView) { this.absentList = absentList; _tableView = tableView; } // 保留原有RowsInSection、RowSelected等方法... void LongPressMethod(UILongPressGestureRecognizer gestureRecognizer) { if (gestureRecognizer.State == UIGestureRecognizerState.Began) { if (gestureRecognizer.View is UITableViewCell cell) { var indexPath = _tableView.IndexPathForCell(cell); if (indexPath != null && indexPath.Row < absentList.Count) { var targetData = absentList[indexPath.Row]; Toast.MakeToast($"获取到数据:{targetData.BandValue}") .SetTitle(targetData.ToString()) .SetDuration(ToastDuration.Regular) .Show(); } } } } }
初始化适配器时传入TableView:
var adapter = new AbsetAdapterClass(absentDataList, yourTableView); yourTableView.Source = adapter;
关键注意点
- 方案一必须清理重复手势:TableViewCell复用机制会导致同一个单元格被多次添加手势,不清理会触发多次回调。
- 方案二必须持有TableView引用:否则无法通过单元格反向获取索引路径。
内容的提问来源于stack exchange,提问作者Mohammed Moghazy
相关产品推荐
相关产品推荐

