IOS中的按钮操作问题

时间:2013-03-20 13:59:57

标签: ios6

这是我用过的代码。

在View Controller A中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(50, 50, 70, 40)];
    [button setTitle:@"Next View" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(nextView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void) nextView
{
    SecondviewController *secondView = [[SecondviewController alloc] init];

    [self.view addSubview:secondView.view];
}

在View Controller B中:

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(50, 50, 70, 40)];
    [button setTitle:@"Previous View" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(previousView) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

-(void) previousView
{

    [self.view removeFromSuperview];
}

问题:当我点击视图控制器B中的按钮时,它不会切换回视图控制器A ......

2 个答案:

答案 0 :(得分:0)

您没有切换viewControllers,而是从viewController B获取视图并将其作为子视图添加到viewController A中。

这里:

     SecondviewController *secondView = [[SecondviewController alloc] init];
    [self.view addSubview:secondView.view];

您需要导航到新视图控制器 ...将其替换为例如

    SecondviewController *secondViewController = [[SecondviewController alloc] init];       
    [self presentViewController:secondViewController animated:YES completion:NIL];

(在命名控制器时最好包括'controller'以避免与其视图混淆)

然后返回,你需要关闭呈现的viewcontroller ......

在ViewControllerB中替换它:

   [self.view removeFromSuperview];

使用

[[self presentingViewController] dismissViewControllerAnimated:YES completion:NIL];

这是从呈现的viewController - viewController B发回消息到呈现viewController,viewControllerA,它执行实际的解散。

答案 1 :(得分:0)

不是将第二个子视图添加到第一个子视图,而是需要在堆栈中显示或推送视图控制器。您只需将其添加为子视图。

 SecondviewController *secondView = [[SecondviewController alloc] init];
 [self presentViewController:secondView animated:NO completion:nil];

在你关闭它的第二个视图控制器中,你可以简单地从堆栈中解除/弹出它。

 [self dismissViewControllerAnimated:YES];