【问题标题】:Xcode - Using Delegate and Segue to Unlock button in first ViewControllerXcode - 在第一个 ViewController 中使用 Delegate 和 Segue 解锁按钮
【发布时间】:2014-05-14 12:18:13
【问题描述】:

我有一个简单的项目,当按下第二个 ViewController (SecondViewController) 上的按钮时,Delegate 函数会向第一个 ViewController 发送一个字符串并取消隐藏一个不可见的新按钮。

我现在这样做没有问题,但是,如果我在这些视图之间添加第三个视图到窗口,该功能将停止工作。

我的意思是:

为了做到这一点,我使用

在 ViewController.h 中:

@interface ViewController : UIViewController <SecondViewControllerDelegate>

在 ViewController.m 中,我实现了一个 Segue 函数,它检测到一个标识符并将值发送到第二个视图:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"to2"]) {
        SecondViewController *SecondView = segue.destinationViewController ;
        SecondView.delegate = self;
    }
}

-(void)done:(UIButton*)name{
    [self dismissViewControllerAnimated:YES completion:nil];
    NSLog(@"back to first view, name=%@ ", name);
    level2But.hidden = NO;

}

要返回第一个窗口,我在 SecondViewController.h 中创建了一个 returnButton:

@protocol SecondViewControllerDelegate <NSObject>
-(void) done:(UIButton*)returnButton; //variable passed to ViewController

@end


@interface SecondViewController : UIViewController{


    IBOutlet UIButton *returnButton;
    id delegate; //declare delegate as an object

}

@property (nonatomic, strong) id <SecondViewControllerDelegate> delegate;


-(IBAction)returnButtonPressed:(id)sender;

在 SeconViewController.m 我有:

-(IBAction)returnButtonPressed:(id)sender{
    [self.delegate done:returnButton];

}

这段代码工作得很好但是如果我有第三个视图它会停止工作。

这已经不行了。

有什么建议吗?有什么帮助吗?

这是项目文件:

http://goo.gl/3rJOje

【问题讨论】:

  • 要么您的新视图控制器必须保留委托并将其传递给现在的 第三个 视图控制器,或者您可以使用 NSNotificationCenter 而不必担心有多少新控制器位于您创建的前两个控制器之间。
  • 这完全是一个新问题.. 为什么它是重复的?????????使用新代码 ---
  • 嗨 Phillip,我要如何使用 NSNotificationCenter 才能不担心中间视图?
  • 不要告诉代理你已经完成了,而是用returnButton 作为通知对象发布通知。让您的第一个视图控制器监听通知并调用 done: 方法作为响应。

标签: ios objective-c xcode uiviewcontroller


【解决方案1】:

我确实检查了您的代码,我可以看到 self.delegate 为 nil,因此您无法在 SecondViewController.m 中移动。

-(IBAction)returnButtonPressed:(id)sender{

[self.delegate done:returnButton];

}

所以请确保您通过了委托。

另外,如果您想知道如何传递数据(委托),请阅读以下教程:

http://www.appcoda.com/storyboards-ios-tutorial-pass-data-between-view-controller-with-segue/

【讨论】:

  • 如何将委托传递给第一个视图?
  • 首先:将故事板标识符添加到中间视图控制器并创建一个委托属性,然后在 segue 中首先将委托从第一个视图控制器传递到第二个视图控制器,然后从第二个视图控制器传递到第二个视图控制器。然后它会工作。
  • 我尝试创建 @protocol MiddleViewControllerDelegate 并将其传递给 Segue,我已向其添加了一个标识符,但它不起作用
  • 从第二个视图中,如果单击继续按钮,它将返回中间视图而不是开始视图控制器
  • 把修改后的代码发给我.. 这样我可以检查并告诉你。您还添加了中间 viewControllerFile .h 和 .m 吗?
猜你喜欢
  • 2018-01-18
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多