UI第三节——UIView详解

时间:2023-03-08 20:30:15
- (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];
}

UI第三节——UIView详解

一个 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

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