首页 > 解决方案 > UIViewController 存在和关闭

问题描述

我的代码中有 3 个视图控制器可用。我编写了代码以从第一个视图控制器呈现第三个视图控制器。

第三个视图控制器中有 2 个按钮可用。(完成和取消)。当我点击完成按钮时,需要存在第二个视图控制器。

如何为此编写代码?

标签: iosobjective-c

解决方案


首先,我建议您必须搜索并查看Objective-C文档和示例。但是有一个基本的如何呈现一个UIViewController

SecondViewController *controller = [SecondViewController new];

如果你想使用完成块

[self presentViewController:controller animated:YES completion:^{

}];

或者如果你想作为礼物使用。

[self presentViewController:controller animated:YES completion:nil];

// 编辑部分

所以我假设按钮如下所示。

UIButton *toGoSecond;
UIButton *toGoThird;

然后在viewDidLoad方法中,您可以assign对这些按钮执行操作。

[toGoSecond addTarget:self action:@selector(goToSecond) forControlEvents:UIControlEventTouchUpInside];
    [toGoThird addTarget:self action:@selector(goToThird) forControlEvents:UIControlEventTouchUpInside];

还有演示处理函数。

-(void) goToSecond{
    SecondController *second = [SecondController new];
    [self presentViewController:second animated:TRUE completion:nil];
}

-(void) goToThird{
    ThirdController *thirdController = [ThirdController new];
    [self presentViewController:thirdController animated:TRUE completion:nil];
}

我认为稍微搜索和查看教程可以让您清楚您的问题,我希望编辑的答案对您有所帮助。

// 最后编辑

嘿,当我回答这个问题时,我无法完全解决你的问题,但我会用委托模式处理你的问题。

我创建了 3 个名为ViewController, SecondViewController, 的控制器ThirdViewController

所以我们开始吧。

创建一个协议。

@protocol ProtocolName
-(void) go;
@end

然后将其分配给您的第一个视图控制器,如下所示。

@interface ViewController : UIViewController<ProtocolName>

比在 ViewController.m 文件中填充 go 方法。

- (void)go{
    NSLog(@"triggered");
    SecondViewController *second = [SecondViewController new];
    [self presentViewController:second animated:TRUE completion:nil];
}

然后在ThirdController.h文件中放入delegateasweak变量。

@interface ThirdViewController : UIViewController
@property (nonatomic,weak) id<ProtocolName> delegate;
@end

ThirdViewControllerFirstViewController分配到它的代表之前,如下所示。

-(void) goToThird{
    ThirdViewController *thirdController = [ThirdViewController new];
    [thirdController setDelegate:self];
    [self presentViewController:thirdController animated:TRUE completion:nil];
}

然后,如果您按下您的按钮SecondViewController,请实现如下所示的按钮操作方法。

- (void) targetMethod{
    [self dismissViewControllerAnimated:YES completion:nil];
    [_delegate go];
}

首先,您必须解除您当前的ThirdViewController委托,然后代表有工作和演示SecondViewController


推荐阅读