zoukankan      html  css  js  c++  java
  • UI第三节——UIView详解

    - (void)viewDidLoad {
        [super viewDidLoad];
    
        UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];
        redView.backgroundColor = [UIColor redColor];
        [self.view addSubview:redView];
        
        // frame,位置的描述
        NSLog(@"frame = %@", NSStringFromCGRect(redView.frame));
        
        // bounds,大小的描述,它的原点,永远都是0, 0
        NSLog(@"bounds = %@", NSStringFromCGRect(redView.bounds));
        
        // 中心点
        NSLog(@"center = %@", NSStringFromCGPoint(redView.center));
        
        // 标签,用来标识这个view的
        redView.tag = 100;
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(20, 160, 335, 30);
        [btn setTitle:@"Change Color" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:btn];
    }
    
    - (void)btnClicked:(UIButton *)btn
    {
        // 根据Tag值来取得对应的View
        UIView *redView = [self.view viewWithTag:100];
        redView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0f];
    }
    

     

    一个 UIView 里面可以包含许多的 Subview(其他的 UIView),而这些 Subview 彼此之间是有所谓的阶层关系,这有点类似绘图软体中图层的概念,下面程式码示演示了几个在管理图层(Subview)上常用的方法,其程式码如下。
     
    1.首先是大家最常使用的新增和移除Subview。
     
    [Subview removeFromSuperview];     //将Subview从当前的UIView中移除 
    [UIView addSubview:Subview];     //替UIView增加一个Subview  

    2.在UIView中将Subview往前或是往后移动一个图层,往前移动会覆盖住较后层的 Subview,而往后移动则会被较上层的Subview所覆盖。
     
    [UIView bringSubviewToFront:Subview];       //将Subview往前移动一个图层(与它的前一个图层对调位置)//将Subview往前移动一个图层(与它的前一个图层对调位置)

    [UIView sendSubviewToBack:Subview];      //将Subview往后移动一个图层(与它的后一个图层对调位置)

      
    3.在UIView中使用索引Index交换两的Subview彼此的图层层级。

    [UIView exchangeSubviewAtIndex:indexA withSubviewAtIndex:indexB];    //交换两个图层  
     
    4.使用Subview的变数名称取得它在UIView中的索引值(Index )。
    NSInteger index = [[UIView subviews] indexOfObject:Subview名称];       //取得Index  
     
    5.替Subview加上NSInteger 的註记(Tag)好让之后它们分辨彼此。
      
    [Subview setTag:NSInteger];       //加上标记
    [UIView viewWithTag:NSInteger];  //通过标记得到view 返回值为UIView
     
    6.最后是取得UIView中所有的Subview,呼叫此方法会传回一个 NSArray,并以由后往前的顺序列出这些 Subview,下图中是列出范例图片里Root中所有的Subview。
     
    [UIView subviews] ;        //取的UIView下的所有Subview

     如果对你有帮助,请关注我哦!

  • 相关阅读:
    几种常用的排序算法
    Charles 抓包工具安装和采坑记录
    当你骂特朗普的时候你究竟在骂什么
    苹果公司的另一面:沃兹尼亚克
    网络爬虫设计中需要注意的几个问题
    微信小程序 canvas 绘图问题总结
    自己动手做智能家居之:智能空调控制
    Allegro导入PADS文件
    C#
    C#
  • 原文地址:https://www.cnblogs.com/laolitou-ping/p/6236853.html
Copyright © 2011-2022 走看看