如何将一个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中放入的顺序有关。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值