20150701_UI之UIView层操作

本文介绍了一个iOS应用中视图的层级管理方法,包括如何添加、调整层级以及改变视图的透明度等操作。通过具体的代码示例展示了如何在ViewController中实现不同颜色视图的添加与层级调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码实例:

//
//  ViewController.m
//  IOS150701_UI(01)_UIVieew层操作
//
//  Created by PengJunlong on 15/7/1.
//  Copyright (c) 2015年 Peng Junlong. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIView *redview = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 320, 100)];
    redview.backgroundColor = [UIColor redColor];
    [self.view addSubview:redview];
    UIView *greenview = [[UIView alloc] initWithFrame:CGRectMake(20, 140, 320, 100)];
    greenview.backgroundColor = [UIColor greenColor];
    greenview.alpha = 0.8;
    [self.view addSubview:greenview];
    UIView *yellowView = [[UIView alloc] initWithFrame:CGRectMake(30, 180, 320, 100)];
    yellowView.backgroundColor = [UIColor yellowColor];
    yellowView.alpha = 0.8;
    [self.view addSubview:yellowView];
    //先添加的视图在self.view的最底层,后添加的视图在self.view的最顶层,可以设置透明度显示后面的视图yellowView.alpha = 0.8;
    
    //父视图       子视图
    //获取父视图
    UIView *superView = [redview superview];    //获取子视图获取对应的父视图
    superView.backgroundColor = [UIColor cyanColor];
    
    //获取子视图
    //最底层视图在数组的0位置,在默认情况下系统会帮我们创建两个透明的视图,可以在Main.storyboard中将Use Auto Layout和Use Size Classes不勾选,去掉这两个图层
    NSArray *subViewArr = [self.view subviews];
    ((UIView *)[subViewArr objectAtIndex:0]).backgroundColor = [UIColor grayColor];
    
    //把子视图移动到最顶层显示
    [self.view bringSubviewToFront:redview];
    //把子视图移动到最底层显示
    [self.view sendSubviewToBack:yellowView];
    
    UIView *insertView = [[UIView alloc] initWithFrame:CGRectMake(25, 160, 320, 100)];
    insertView.backgroundColor = [UIColor blueColor];
    //在指定下标位置添加视图
    //[self.view insertSubview:insertView atIndex:1];
    //在指定视图的上方插入视图
    //[self.view insertSubview:insertView aboveSubview:greenview];
    //在指定的视图下方插入视图
    [self.view insertSubview:insertView belowSubview:yellowView];
    [self.view exchangeSubviewAtIndex:0 withSubviewAtIndex:1];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值