UIView视图层次

#import "AppDelegate.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] autorelease];

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

    

    self.window.rootViewController = [[UIViewController alloc]init];

    

    UIView *backView = [[UIView alloc] initWithFrame:self.window.bounds];

    

    NSArray *color = @[[UIColor redColor],[UIColor yellowColor],[UIColor blueColor],[UIColor greenColor]];

    for (int i = 0; i<color.count; i++) {

        UIView *view =[[UIView alloc]initWithFrame:CGRectMake(50+40*i, 50+40*i, 200, 200)];

        view.backgroundColor = color[i];

        view.tag = 100+i;

        [backView addSubview:view];

        //[self.window addSubview:view];

        [view release];

        

    }

   

    NSLog(@"%@",backView.subviews);

    NSLog(@"===================");

    UIView *redView = [backView viewWithTag:100];

    //把视图移动到最高层

    //[backView addSubviewToFront:redView];

    

   [backView addSubview:redView];

    

    NSLog(@"%@",backView.subviews);

    

    UIView *greenView = [backView viewWithTag:103];

    //把视图移动到最顶层

    [backView sendSubviewToBack:greenView];

    

    

    

    

    UIView *yellowView = [backView viewWithTag:101];

    UIView *blueView = [backView viewWithTag:102];

    //交换两个视图的层次

    

    [backView exchangeSubviewAtIndex:[backView.subviews indexOfObject:yellowView] withSubviewAtIndex:[backView.subviews indexOfObject:blueView]];

    

    

    

    

    UIView *blackView = [[UIView alloc]initWithFrame:CGRectMake(180, 20, 20, 300)];

    

    

    

    //插入到指定的下标中

    [backView insertSubview:blackView atIndex:1];

    

    [backView release];

    

    

    //插入到指定视图的上面

    [blackView insertSubview:blackView aboveSubview:yellowView];

    

    

    [blackView release];

    

    //在父视图上移除子视图

    [blackView removeFromSuperview];

    NSLog(@"%@",blackView.subviews);

    

    return YES;

}

原文地址:https://www.cnblogs.com/chunji/p/5257441.html