代码实例:
//
// ViewController.m
// IOS150701_UI(01)_UIVieew层操作
//
// Created by PengJunlong on 15/7/1.
// Copyright (c) 2015年 Peng Junlong. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *redview = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 320, 100)];
redview.backgroundColor = [UIColor redColor];
[self.view addSubview:redview];
UIView *greenview = [[UIView alloc] initWithFrame:CGRectMake(20, 140, 320, 100)];
greenview.backgroundColor = [UIColor greenColor];
greenview.alpha = 0.8;
[self.view addSubview:greenview];
UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(30, 180, 320, 100)];
yellowView.backgroundColor = [UIColor yellowColor];
yellowView.alpha = 0.8;
[self.view addSubview:yellowView];
//先添加的视图在self.view的最底层,后添加的视图在self.view的最顶层,可以设置透明度显示后面的视图yellowView.alpha = 0.8;
//父视图 子视图
//获取父视图
UIView *superView = [redview superview]; //获取子视图获取对应的父视图
superView.backgroundColor = [UIColor cyanColor];
//获取子视图
//最底层视图在数组的0位置,在默认情况下系统会帮我们创建两个透明的视图,可以在Main.storyboard中将Use Auto Layout和Use Size Classes不勾选,去掉这两个图层
NSArray *subViewArr = [self.view subviews];
((UIView *)[subViewArr objectAtIndex:0]).backgroundColor = [UIColor grayColor];
//把子视图移动到最顶层显示
[self.view bringSubviewToFront:redview];
//把子视图移动到最底层显示
[self.view sendSubviewToBack:yellowView];
UIView *insertView = [[UIView alloc] initWithFrame:CGRectMake(25, 160, 320, 100)];
insertView.backgroundColor = [UIColor blueColor];
//在指定下标位置添加视图
//[self.view insertSubview:insertView atIndex:1];
//在指定视图的上方插入视图
//[self.view insertSubview:insertView aboveSubview:greenview];
//在指定的视图下方插入视图
[self.view insertSubview:insertView belowSubview:yellowView];
[self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end