无法解雇presentModalViewController

时间:2012-10-30 12:11:49

标签: iphone uiviewcontroller presentmodalviewcontroller

我在iphone应用程序中有两个视图控制器。

1。)FirstVC

2。)SecondVC

在我的FirstVC中我有一个按钮。通过点击该按钮,我在presentModalViewController中打开了SecondVC。看下面的代码。

- (IBAction)buttonClicked:(id)sender
{
    SecondVC *secondVC = [SecondVC alloc] initWithNibName:@"SecondVC" bundle:nil];
    [self.navigationController presentModalViewController:secondVC animated:YES];
}

现在转移到SecondVC。在SecondVC上,我创建了导航栏以及“取消”按钮作为leftBarButtonItem。我在取消按钮上设置了一个单击按钮的事件。在那种方法中,我想解雇SecondVC。波纹管方法在SecondVC中。看下面的代码。

- (void)cancelButtonClicked
{
  [self dismissModalViewControllerAnimated:YES];
}

这段代码不起作用。我无法通过此代码解雇SecondVC。请提出其他技巧。

4 个答案:

答案 0 :(得分:5)

将按钮代码更改为此..

- (IBAction)buttonClicked:(id)sender
{
    SecondVC *secondVC = [SecondVC alloc] initWithNibName:@"SecondVC" bundle:nil];
 [self presentViewController:secondVC animated:YES completion:NULL];

}

on cancelButtonClick

-(void)cancelButtonClicked {
 [self.presentingViewController dismissViewControllerAnimated:YES completion:NULL];

}

答案 1 :(得分:3)

您正在将dismissModalViewControllerAnimated:消息发送到错误的对象。

由于您通过导航控制器呈现了模态视图控制器,因此您应该调用:

[self.presentingViewController dismissModalViewControllerAnimated:YES];

这适用于iOS 5及更高版本。如果您只针对iOS 5及更新版本,您还可以考虑使用其上可用的较新方法来管理模态视图控制器:

– presentViewController:animated:completion:
– dismissViewControllerAnimated:completion:

但我不认为这是强制性的。

如果您想支持iOS 4及更早版本,则应向模态视图控制器添加属性:

@interface SecondVC : UIViewController
@property (nonatomic, weak/assign) UIViewController* presentingController;
...
@end

并在模态显示控制器之前设置它:

- (IBAction)buttonClicked:(id)sender
{
     SecondVC *secondVC = [SecondVC alloc] initWithNibName:@"SecondVC" bundle:nil];
     secondVC.presentingController = self.navigationController;
     [self.navigationController presentModalViewController:secondVC animated:YES];
}

然后你会用:

[self.presentingController dismissModalViewControllerAnimated:YES];

答案 2 :(得分:0)

尝试使用当前的第二个VC ......

[self presentModalViewController:secondVC animated:YES];

答案 3 :(得分:0)

请使用以下代码替换您的代码

- (IBAction)buttonClicked:(id)sender
{
    SecondVC *secondVC = [SecondVC alloc] initWithNibName:@"SecondVC" bundle:nil];
    [self presentModalViewController:secondVC animated:YES];
}

- (void)cancelButtonClicked
{
   [self dismissModalViewControllerAnimated:YES];
}
相关问题