gpt4 book ai didi

c# - 如何从 UITableView RowSelect Event Monotouch 访问主 UIViewController?

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:44 25 4
gpt4 key购买 nike

我的主 ViewController 上有一个 UITAbleView。 Tableview 是子类,如下所示。当用户选择一行时,我想通过调用主 ViewController 上的例程来切换到新 View 。但是,我无法从子类访问我的主视图 Controller 。我该怎么办?

public class TableSource : UITableViewSource
{
string[] tableItems;
string cellIdentifier = "TableCell";

public TableSource(string[] items)
{
tableItems = items;
}
public override int RowsInSection(UITableView tableview, int section)
{
return tableItems.Length;
}
public override UITableViewCell GetCell(UITableView tableView, MonoTouch.Foundation.NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);
if (cell == null)
cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);
cell.TextLabel.Text = tableItems[indexPath.Row];
return cell;
}

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
new UIAlertView("Row Selected", tableItems[indexPath.Row], null, "OK", null).Show();
tableView.DeselectRow(indexPath, true);

//Call routine in the main view controller to switch to a new view

}

}

最佳答案

我在发现并评论了一篇类似的帖子后偶然发现了这篇帖子: Xamarin UITableView RowSelection

虽然将 UIViewController 的实例传递给 TableSource 是解决此问题的一种方法,但它确实有其缺点。主要是因为您已将 TableSource 与特定类型的 UIViewController 紧密耦合。

我建议改为在您的 UITableViewSource 中创建一个 EventHandler,如下所示:

public event EventHandler ItemSelected;

我还会为所选项目设置一个 getter 属性:

private selectedItem
public MyObjectType SelectedItem{
get{
return selectedItem;
}

}

然后我会像这样更新 RowSelected 方法:

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
selectedItem = tableItems[indexPath.Row];
ItemSelected(this, EventArgs.Empty);
}

您的 UIViewController 然后可以监听 ItemSelected 事件并执行所需的任何操作。这允许您将 UITableViewSource 重用于多个 View 和 View Controller 。

关于c# - 如何从 UITableView RowSelect Event Monotouch 访问主 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15008852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com