在 xamarin iOS 中 - 在 UITableViewCell 中获取 [indexPath.Row],使用按钮

本文关键字:按钮 Row iOS xamarin UITableViewCell 获取 indexPath | 更新日期: 2023-09-27 18:36:40

在Xamarin iOS中 - 我有一个名为TableCell ( public class TableCell : UITableViewCell { } )的类 - 在这个类中我声明了按钮。

在按钮单击事件中,我正在尝试访问UITableViewCell中的[indexPath.Row]。我可以选择一行来查找[indexPath.Row] UITableViewSource.

public class TableSource : UITableViewSource {
//  - - - -
 public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
    {
        new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
        tableView.DeselectRow (indexPath, true); // iOS convention is to remove the highlight
  }
// - - - -
}

如何在UITableViewCell中获取[indexPath.Row],使用按钮单击事件..?

在 xamarin iOS 中 - 在 UITableViewCell 中获取 [indexPath.Row],使用按钮

这不是最好的方法,但它肯定会起作用:

我会用一个新属性扩展 TableCell 类:

public NSIndexPath IndexPath { get; set; }

然后,如果您使用的是单元格重用模式,我会将这一行添加到UITableViewSource的GetCell方法中:

public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
    {
       TableCell cell = tableView.DequeueReusableCell("YourIdentifier") ?? new TableCell();
       cell.IndexPath = indexPath;
       return cell;
    }

之后,您可以在任何地方访问单元格的当前 IndexPath,即:

public TableCell()
{
     UIButton btn = new UIButton(UIButtonType.RoundRect);
     btn.TouchUpInside += (sender, args)
     {
           new UIAlertView("Button pressed!", indexPath.Row, null, "OK", null).Show();
     }
}

使用 VisibleCells 属性。用户选择行后,UITableViewCell将可见。


替代解决方案(如果您想获得相似但不是相同的单元格):你可以使用传递的UITableView tableView通过UITableViewCell.GetCell获取它,然后将其转换为你的UITableViewCell类型,然后使用传递的NSIndexPath indexPath调用它的方法。

像这样:

public class TableSource : UITableViewSource {
    //  - - - -
     public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
        {
        var cell = tableView.GetCell(tableView, indexPath);
        var myCell class = cell as MyCellClass;
        if (myCell != null) {
            // TODO: do something with cell.
        }          
      }
    // - - - -
    }
// - - - -
}