iOS学习之动态创建根视图

一般我们都会使用StoryBoard来进行界面开发,今天学习下,如何不使用StoryBoard的情况下,自己通过代码创建视图。
首先,新建项目去掉Main.storyboard,并在项目设置里面去掉storyboard的关联。

Paste_Image.png

我们只在AppDelegate里面进行编码。
代码如下:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 动态创建视图
    // 去掉项目设置里面的Deployment Info -> Main Interface
    // 此时window = nil
    // 创建Window ,大小为整个屏幕大小
    self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor redColor];
    // XCode 高版本需要设置rootViewController
    UIViewController *viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
    self.window.rootViewController = viewController;
    [self.window makeKeyAndVisible];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    [view setBackgroundColor:[UIColor greenColor]];
    [self.window addSubview:view];
    
    // 创建一个Label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 40, 100, 40)];
    label.text = @"Hello";
    label.textColor = [UIColor blackColor];
    label.tag = 2;
    [self.window addSubview:label];
    
    // 创建一个button,设置属性,并设置事件
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 130, 100, 40)];
    button.backgroundColor = [UIColor yellowColor];
    [button setTitle:@"Click" forState:UIControlStateNormal];
    [button setHighlighted:TRUE];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.window addSubview:button];
    return YES;
}

-(void)buttonClick:(id)sender{
    // 父容器可以通过Tag来找到相应的View
    UILabel *label = [self.window viewWithTag:2];
    label.text = @"Button Click";
}```

你可能感兴趣的:(iOS学习之动态创建根视图)