以下是一个简单的 iOS 开发中切换视图控制器的示例代码,基于 Objective-C 编写:

在 ViewController.h 文件中:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@end

在 ViewController.m 文件中:

#import "ViewController.h"
#import "SecondViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 创建一个按钮
    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 *secondVC = [[SecondViewController alloc] init];
    
    // 切换视图控制器
    [self.navigationController pushViewController:secondVC animated:YES];
}

@end

在 SecondViewController.h 文件中:

#import <UIKit/UIKit.h>

@interface SecondViewController : UIViewController

@end

在 SecondViewController.m 文件中:

#import "SecondViewController.h"

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor grayColor];
    
    // 创建一个标签
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
    label.text = '第二个视图控制器';
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
}

@end

这段代码中,首先在 ViewController 中创建了一个按钮,当按钮被点击时会调用 switchViewController 方法。在 switchViewController 方法中,创建了一个 SecondViewController 的实例,并将其推入导航控制器的栈中,实现视图控制器的切换。另外,为了演示效果,SecondViewController 中创建了一个标签用于显示文本内容。

注意:为了能够切换视图控制器,需要确保 ViewController 被嵌入到一个导航控制器中。

iOS开发:使用Objective-C实现视图控制器切换的完整代码示例

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

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