如何传递和收集 UITableView 中按下的信息

Posted

技术标签:

【中文标题】如何传递和收集 UITableView 中按下的信息【英文标题】:How to pass and collect info what was pressed in UITableView 【发布时间】:2013-12-05 13:01:08 【问题描述】:

我的第一个 Table View 应用程序需要更多帮助。 我有包含大陆、国家和其他信息的 .plist:

我使用 StoryBoard 并且有 3 个视图控制器(MasterVC - 用于大洲,MiddleVC - 用于国家,DetailVC - 用于详细信息)。我已经在 MysterVC 的 UITableView 中显示了大陆。现在我想传递有关推送到 MiddleVC 的信息,例如,欧洲被推送以及在我的 MiddleVC 的表格视图中显示欧洲国家/地区。

我想我应该在 didSelectRowAtIndexPath 中这样做:

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath

//is it correct way to catch the info about which continent was pressed?
NSString *ContinentName = [[world allKeys] objectAtIndex:indexPath.row];

//I don't know how to pass the info forward


或者我应该使用 segue 来传递数据?

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

if ([[segue identifier] isEqualToString:@"showMiddle"]) 
    NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
    NSDate *object = _objects[indexPath.row];

//??is everything what needed here??

[[segue destinationViewController] setDetailItem:object];


我不确定如何处理来自 MasterVC 的传递信息,在 MiddleVC 中。虽然我准备了一些初始编码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

//I think countries arrays will be needed here
NSArray *namesOfAfricanCountries = [africa allKeys];
NSString *AfricanCountryName = [namesOfAfricanCountries objectAtIndex:indexPath.row];

NSArray *namesOfEuropeanCountries = [europe allKeys];
NSString *EuropeanCountryName = [namesOfEuropeanCountries objectAtIndex:indexPath.row];

//how to feel cells only with the proper continent's countries?
cell.textLabel.text = ???;

return cell;

将不胜感激。

【问题讨论】:

这是一个很好的教程。也许你可以看看link 【参考方案1】:

你在使用 UINavigationController 吗?如果是这样:

    设置从您的主 VC 到您的详细信息 VC 的“推送”segue,并在您的详细信息 VC 中有一个属性来保存“大陆”字典。 实现'prepareForSegue',在这里你可以使用indexPathForCell: 在sender 参数上找出哪个单元格被点击了。 使用索引路径中的行在字典中定位国家 在准备 segue 时,使用 segue.destinationViewController 获取详细信息 VC 的句柄,并将其大陆属性设置为数据源中的国家/地区字典。 (您只想传递包含该大陆国家/地区的大陆字典,而不是您的整个数据源)。

然后在detail VC' cellForRowAtIndexPath:

    那么如果您只想在单元格中显示国家名称,假设名称是键...

NSString *key = [self.continentDict allKeys][indexPath.row];

cell.textLabel.text = key;

【讨论】:

好的,我试试。现在我对 segue 方法有一个奇怪的问题。我用新的标识符命名了我的 segues,并在 segue 方法中也对其进行了更改,并且应用程序一直在崩溃。

以上是关于如何传递和收集 UITableView 中按下的信息的主要内容,如果未能解决你的问题,请参考以下文章

如何将自定义 UIControl 中按下的 UIButton 传递给我的视图控制器?

如何知道 iPhone 键盘中按下的键

如何删除我在 Flex 中按下的按钮?

如何检查在VB中按下的键

如何禁用在android片段类中按下的后退按钮

通过在另一个 ViewController 中按下按钮/在另一个 ViewController 中引用 UITableView 创建 UITableViewCell