以下是一个简单的示例,演示了如何在 iOS 开发中切换视图控制器的代码。请注意,这是 Objective-C 代码。

首先,创建一个新的视图控制器类(例如'SecondViewController'),并在其中添加所需的 UI 元素和逻辑。

// SecondViewController.h
#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

@end

// SecondViewController.m
#import "SecondViewController.h"

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加 UI 元素和逻辑
}

@end

接下来,在当前视图控制器中添加切换视图控制器的代码。

// 当前视图控制器的头文件
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

// 当前视图控制器的实现文件
#import "ViewController.h"
#import "SecondViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 添加一个按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = CGRectMake(100, 100, 200, 50);
    [button setTitle:'切换视图控制器' forState:UIControlStateNormal];
    [button addTarget:self action:@selector(switchViewController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)switchViewController {
    // 创建一个新的 SecondViewController 实例
    SecondViewController *secondViewController = [[SecondViewController alloc] init];
    
    // 使用导航控制器进行视图控制器切换
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:secondViewController];
    navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navigationController animated:YES completion:nil];
}

@end

在这个示例中,我们在当前视图控制器中添加了一个按钮。当用户点击按钮时,'switchViewController'方法会被调用。在该方法中,我们创建了一个新的'SecondViewController'实例,并将其嵌入到一个导航控制器中。然后,我们使用'presentViewController:animated:completion:'方法将导航控制器呈现给用户,实现视图控制器之间的切换。

iOS 开发:使用导航控制器切换视图控制器 (完整示例代码)

原文地址: https://www.cveoy.top/t/topic/o9oE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录