将一个UIView显示在最前面只需要调用其父视图的
将一个UIView层推送到背后只需要调用其父视图的
下面看看代码是如何实现的:
在AppDelegate.h中:
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
ViewController1 *_v1;
ViewController2 *_v2;
}
@property (strong, nonatomic) UIWindow *window;
在AppDelegate.m中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
_v1=[[ViewController1 alloc] init];
_v2=[[ViewController2 alloc] init];
[_window addSubview:_v2.view];
[_window addSubview:_v1.view];
self.window.backgroundColor = [UIColor clearColor];
[self.window makeKeyAndVisible];
return YES;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view setBackgroundColor:[UIColor whiteColor]];
UIButton *btn1=[UIButton buttonWithType:UIButtonTypeRoundedRect];
btn1.frame=CGRectMake(10, 30, 100, 50);
[btn1 setTitle:@"切换" forState:UIControlStateNormal];
btn1.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleBottomMargin;
[btn1 addTarget:self action:@selector(btn1_click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
}
-(void)btn1_click{
NSLog(@"点击111");
[self.view.window sendSubviewToBack:self.view];//这里将v1隐藏到背后
// [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:2];
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"1111111");
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor=[UIColor redColor];
UIButton *btn1=[UIButton buttonWithType:UIButtonTypeCustom];
btn1.frame=CGRectMake(10, 30, 100, 50);
[btn1 setTitle:@"切换" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(btn2_click) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
}
-(void)btn2_click{
NSLog(@"点击2222");
[self.view.window sendSubviewToBack:self.view];//这里将v2隐藏到背后
}
-(void)viewWillAppear:(BOOL)animated
{
NSLog(@"2222222");
}