iOS Objective-C:如何从另一个类调用 Push Segue

Posted

技术标签:

【中文标题】iOS Objective-C:如何从另一个类调用 Push Segue【英文标题】:iOS Objective-C: How to call Push Segue from another Class 【发布时间】:2014-10-21 07:13:29 【问题描述】:

场景

我有一个应用程序可以在 UITableViewController 中向用户显示帖子 - 在某些包含 cmets 的帖子中,该单元格内会有 另一个 UITableView 来显示 cmets。每个评论都将包含一个位于 UIButton 下方的个人资料图片。当这个 UIButton 被推送时,我希望 UITableViewController 类与另一个 UIViewController 相连接,该 UIViewController 将显示有关发布该帖子的用户的信息。

所以,回顾一下

UITableViewController 将执行 Push Segue

UITableViewController 拥有UITableViewCells

UITableViewCells (包含 cmets) 将有一个孩子 UITableView

UITableView 将包含单元格本身,每个单元格都有一个UIButton

UIButton 被推送时,UITableViewController 将执行 Push Segue

我的尝试

- (void)ProfilePictureWasPushed:(UIButton *)sender 

    NSDictionary *object = [self.comments objectAtIndex:sender.tag];

    DashboardViewController *dashboard = [[DashboardViewController alloc]init];
    dashboard.selectedID = object[@"posterID"];
    [dashboard performSegueWithIdentifier:@"profile" sender:dashboard];


我收到此错误...

...reason: 'Receiver (<DashboardViewController: 0x7d867600>) has no segue with identifier 'profile''

我已经检查过,实际上有一个叫做“profile”的 push segue。

问题

有谁知道如何正确执行此壮举?

【问题讨论】:

【参考方案1】:

根据此处https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/index.html#//apple_ref/occ/instm/UIViewController/performSegueWithIdentifier:sender 的文档,必须使用情节提要加载启动和接收segues 的UIViewController:

接收此消息的视图控制器必须是从情节提要中加载的。如果视图控制器没有关联的故事板,可能是因为你自己分配和初始化了它,这个方法会抛出异常。

如果您想从 ViewControllerA 转移到 ViewControllerB,那么您需要在 ViewControllerA 的实例上调用该方法。此外,您不应该创建 ViewControllerB。所以你的代码应该是

- (void)ProfilePictureWasPushed:(UIButton *)sender 
    [self performSegueWithIdentifier:@"profile" sender:sender]; //self could also be used for sender

由于您还想通过 segue 将数据传递给目标视图控制器,因此要覆盖源视图控制器(即您的 UITableViewController)中的 -prepareForSegue:sender,检索目标视图控制器并设置 selectedID。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
     if ([[segue identifier] isEqualToString:@"profile"]]) 
         NSDictionary *object = [self.comments objectAtIndex:sender.tag];
         DashboardViewController *dashboard = (DashboardViewController *)segue.destinationViewController;
         dashboard.selectedID = object[@"posterID"];
      

【讨论】:

我知道这是对这个答案的一个非常迟的检查(已经过了一年多),但你仍然是正确的。现在回头看问题是很明显的,你完美地概述了它们。即使现在问它我也觉得很傻,但如果它对其他用户有帮助,我会继续为他们提供。【参考方案2】:

'profile' segue 标识符是否位于 DashboardViewController 上?请在项目的 Main.storyboard 上查看。

示例: 位于 MyViewController 场景中的此项目的“海报”转场

【讨论】:

【参考方案3】:

字符串“profile”应该在情节提要中明确指定。在界面构建器中选择 segue,然后转到 Attributes Inspector 并检查 Indetifier 是否已定义且拼写正确。

【讨论】:

以上是关于iOS Objective-C:如何从另一个类调用 Push Segue的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C 从另一个类访问 @private 实例变量

IOS/Objective-C:调用另一个类(VC)方法不起作用

如何从另一个类调用@selector 方法

如何从另一个类调用方法函数?

Swift:如何从另一个类 X 更新 UILabel:UIButton

如何从另一个类调用 QMainWindow 组件?