前面我们大致了解了UIView的情况,当然,日常的开发中,UIView还需要更多的功能,其中最多的,就是UIView的嵌套,下面就来了解一下:
利用addSubView方法在UIView追加子元素,这里我们依然用前面的代码进行添加:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// label
self.window.backgroundColor = [UIColor blueColor];
UILabel *label = [[UILabel alloc]initWithFrame:CGRectZero];
label.frame = CGRectMake(0, 0, 200, 50);
label.center = CGPointMake(160, 240);
label.text =@"UIView";
label.textColor = [UIColor redColor];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor clearColor];
[self.window addSubview:label];
//加按钮
//这里就按钮的基本设置做了简要介绍,以后有机会,会就UIButton的更多用法做详细介绍
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(120, 50, 80, 60);
button.backgroundColor = [UIColor whiteColor];
[button setTitle:@"butto" forState:UIControlStateNormal];
[self.window addSubview:button];
//加图片
//这里注意,我一开始老是以为初始化了UIImage,就能直接加到主界面上,其实完全错了,一定要先初始化UIImage,在初始化UIImageView作为image的载体,加载到主界面
UIImage *image = [UIImage imageNamed:@"1"];
UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
imageView.frame = CGRectMake(100, 150, image.size.width, image.size.height);
[self.window addSubview:imageView];
[self.window makeKeyAndVisible];
return YES;
}
效果图如下:
今天就到这儿,晚安!