如何將一個uiview推送到窗口的前面與背後

將一個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;

}

在V1中:

- (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");

}

在V2中:(這裏基本和v1中相似)

- (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");

}


當視圖加載後我們會發現v2首先是在v1前面的。。。。這和我們在UIwindow中放入的順序有關。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章