如何将一个uiview推送到窗口的前面与背后

来源:互联网 发布:bl漫画肉软件 编辑:程序博客网 时间:2024/05/17 06:13

将一个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 = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

    

    _v1=[[ViewController1alloc] init];

    _v2=[[ViewController2alloc] init];

    [_windowaddSubview:_v2.view];

    [_windowaddSubview:_v1.view];

    self.window.backgroundColor = [UIColorclearColor];

    [self.windowmakeKeyAndVisible];

    return YES;

}

在V1中:

- (void)viewDidLoad

{

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    [self.viewsetBackgroundColor:[UIColorwhiteColor]];

    UIButton *btn1=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    btn1.frame=CGRectMake(10,30, 100, 50);

    [btn1 setTitle:@"切换"forState:UIControlStateNormal];

    btn1.autoresizingMask=UIViewAutoresizingFlexibleLeftMargin |UIViewAutoresizingFlexibleBottomMargin;

    [btn1 addTarget:selfaction:@selector(btn1_click)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn1];

}


-(void)btn1_click{

   NSLog(@"点击111");

    [self.view.windowsendSubviewToBack:self.view];//这里将v1隐藏到背后

   // [self.view exchangeSubviewAtIndex:1 withSubviewAtIndex:2];

}

-(void)viewWillAppear:(BOOL)animated

{

    NSLog(@"1111111");

}

在V2中:(这里基本和v1中相似)

- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view.

    self.view.backgroundColor=[UIColorredColor];

    UIButton *btn1=[UIButtonbuttonWithType:UIButtonTypeCustom];

    btn1.frame=CGRectMake(10,30, 100, 50);

    [btn1 setTitle:@"切换"forState:UIControlStateNormal];

    [btn1 addTarget:selfaction:@selector(btn2_click)forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn1];

}


-(void)btn2_click{

   NSLog(@"点击2222");

    [self.view.windowsendSubviewToBack:self.view];//这里将v2隐藏到背后

}


-(void)viewWillAppear:(BOOL)animated

{

    NSLog(@"2222222");

}


当视图加载后我们会发现v2首先是在v1前面的。。。。这和我们在UIwindow中放入的顺序有关。


0 0