一般我們都會使用StoryBoard來進行界面開發(fā)雏亚,今天學習下盛卡,如何不使用StoryBoard的情況下系任,自己通過代碼創(chuàng)建視圖新症。
首先步氏,新建項目去掉Main.storyboard,并在項目設置里面去掉storyboard的關(guān)聯(lián)。
Paste_Image.png
我們只在AppDelegate里面進行編碼徒爹。
代碼如下:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// 動態(tài)創(chuàng)建視圖
// 去掉項目設置里面的Deployment Info -> Main Interface
// 此時window = nil
// 創(chuàng)建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];
// 創(chuàng)建一個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];
// 創(chuàng)建一個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";
}```