iOS代码实现布局(一)—不使用StoryBoard和Xib

最近在学习ios开发,因为是团队开发所以在写布局的时候就不使用StoryBoard和Xib了,直接纯代码来设计布局。

删除相关文件和设置配置信息

删除StoryBoard

直接Move to Trash即可
在这里插入图片描述

去掉Info.plist里面的信息

点击减号即可
在这里插入图片描述

修改项目信息

将Main Interface置空
在这里插入图片描述

在AppDelegate中设置

把StoryBoard删掉之后,我们就必须手动创建一个Viewcontroller并且设置其为根控制器
注意要导入相应的类
AppDelegate.h

#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>{
    UIWindow * window;
    ViewController * viewController;
}

@property (nonatomic, strong) UIWindow * window;
@property (nonatomic, strong) ViewController * viewController;

@end

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]];//创建一个Window
        self.window.backgroundColor=[UIColor whiteColor]; //
        self.viewController= [[ViewController alloc] init]; //创建一个VC
        UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:self.viewController];
    //    nav.navigationBar.hidden = YES;
        self.window.rootViewController=nav; //设置好根视图控制器
        [self.window makeKeyAndVisible]; //设置这个window为主(key)窗口并设置成为可见
    return YES;
}

记住要把下面的部分注释掉
在这里插入图片描述
然后在ViewController.h里和ViewController.m设计的你的布局就OK了。然后运行。

运行后黑屏问题

在AppDelegate和ViewController都设置好后运行,没有报错但是黑屏。那么问题出在哪里呢?
编译器显示的问题是:[WindowScene] There is no scene delegate set. A scene delegate class must be specified to use a main storyboard file.
解决方法:将Info.plist -> Open As -> Source Code将划框的部分删除。
在这里插入图片描述
然后就可以运行成功,显示自己设计的界面啦。


版权声明:本文为qq_43133382原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。