【iOS】ObjectiveC 开发:不使用 Main.storyboard 初始化项目

188 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第 3 天,点击查看活动详情

ObjectiveC 开发:初始化项目

使用 storyboard 能够可视化的快速构建产品原型, 但是在团队合作开发过程中一旦产生文件冲突处理起来就会比较麻烦.

因此老式的手写 UI 方法仍然是合作开发的主流方法. 本文从新建项目开始, 撤销与模板项目中与 storyboard 有关的配置.

版本需求

  • XCode 版本 13.4.1

初始化项目

1. 删除 Main interface 中的配置项

将项目配置页 General 条目里的 Main Inteface 中的内容删除.

image.png

2. 将 Info.plist 从项目中排除

注意不可以删除, 只要将之排除即可, 设置位置是 Target Membership, 取消勾选.

原本版本中的大部分 Info 的 Key-Value 对都转移至第一步的项目配置页顶部的 Info 条目中了.

image.png

3. 编辑文件

  1. 删除两个 SceneDelegate 文件, 此时的文件树如下所示.
.
├── AppDelegate.h
├── AppDelegate.m
├── Assets.xcassets
│   ├──... 
├── Info.plist
├── ViewController.h
├── ViewController.m
└── main.m
  1. 在 AppDelegate.m 中增加窗口初始化逻辑.
#import "AppDelegate.h"
#import "ViewController.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    ViewController *vc = [[ViewController alloc] init];
    self.window.rootViewController = vc;
    [self.window makeKeyAndVisible];
    return YES;
}

@end
  1. 在 ViewController.m 中增加测试.
#import "ViewController.h"


@interface ViewController ()

@property (strong, nonatomic) UIButton* button;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.button =
        [[UIButton alloc]
         initWithFrame:CGRectMake(0, 100, [[UIScreen mainScreen] bounds].size.width, 20)];
    [self.button setTitle:@"PRINT!" forState:UIControlStateNormal];
    [self.button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.button];
    [self.button addTarget:self
                    action:@selector(clickMe:)
          forControlEvents:UIControlEventTouchUpInside];
}

- (void)clickMe:(id)sender {
    NSLog(@"Hello, world!");
}

@end
  1. 运行即可.