【问题标题】:How to get [tableView indexPathForSelectedRow] From a different View [duplicate]如何从不同的视图中获取 [tableView indexPathForSelectedRow] [重复]
【发布时间】:2014-03-07 03:14:13
【问题描述】:

在我的 TableViewController.m 中,我可以通过执行 [tableView indexPathForSelectedRow] 轻松获取所选行,但我想从 DIFFERENT 视图中获取此值。所以当我的 TableViewController 转到我的 DetailViewController 时。我希望我的 DetailViewController 拥有所选单元格的数据。

【问题讨论】:

  • 你只需要 TableView 的地址。

标签: objective-c xcode uitableview


【解决方案1】:

在适当的架构中,控制器被设计成对其他控制器充当黑盒。在您的示例中,Details 控制器搜索 TableViewController 的选定项目并不是一个很好的做法。相反,您的 TableViewController 应该将 DetailViewController 用作“服务”,并以某种方式将所选对象作为参数传递,或者将其设置为“服务提供者”(DetailController)的属性。 例如

// this is still the TavleViewController's code
id selectedObject = // ... get selected object somehow... indexPathForSelectedRow or whatever
DetailViewController *newView = [[DetailViewController alloc] initWithNibName:@"DetailViewController" bundle:nil];
[newView showDetails:selectedObject];

这里,函数 showDetails 只是一个例子,它是你实现的一个函数,用来传递选择的对象作为参数。

编辑: 你怎么做取决于你的模型。假设模型中的每个对象都代表一个人。您的 MainTableView 有一个名称列表,而 detailView 显示有关所选人员的详细信息。在这种典型的情况下,您将有一个表示 Person 的类,并且人员列表将位于数组中的某个位置。所以...

NSIndexPath *i = [tableView indexPathForSelectedRow];
Person *selectedPerson = [self.myArrayOfPersons objectAtIndex:i.row];
// here you instantiate or show the details view
[detailsView showDetails:selectedPerson]; // this is one option, you could also use a property
// for example
detailsView.selectedPerson = selectedPerson; // this is an alternative to the showDetails, 

在 DetailsViewController 中你可以有这样的东西

- (void)showDetails:(Person *)person
{
    // just fill your controls witht the person's information: age, birth place, address...
    [self.someTextView setText:person.name]
}

【讨论】:

  • 所以对于我的例子,我想分享 NSIndexPath *i = [tableView indexPathForSelectedRow];我的 showDetails 函数究竟会是什么样子?
猜你喜欢
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 2019-09-05
  • 1970-01-01
  • 2012-10-24
相关资源
最近更新 更多