在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]
,使用按钮单击事件..?
这不是最好的方法,但它肯定会起作用:
我会用一个新属性扩展 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.
}
}
// - - - -
}
// - - - -
}