將一個UIView顯示在最前面只需要調用其父視圖的 bringSubviewToFront()方法。
將一個UIView層推送到背後只需要調用其父視圖的 sendSubviewToBack()方法。
下面看看代碼是如何實現的:
在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");
}