iOS專案開發實戰——UIView的子檢視和父檢視

乞力馬紮羅的雪CYF發表於2015-09-25

      iOS控制元件其實是有父子關係的,可以進行相互包含。我們通過程式碼來演示一下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  
  UIView *view1 = [[UIView alloc] init];
  view1.frame = CGRectMake(50, 50, 200, 200);
  view1.backgroundColor = [UIColor yellowColor];
  [self.view addSubview:view1];
  
  //frame是實際檢視大小;
  CGFloat x = view1.frame.origin.x;//獲取view的橫座標;
  CGFloat y = view1.frame.origin.y;//獲取view的縱座標;
  CGFloat width = view1.frame.size.width;//獲取view的寬度;
  CGFloat height = view1.frame.size.height;//獲取view的高度;
  
  //bounds是邊框大小;x,y永遠為零;
  CGFloat xBounds = view1.bounds.origin.x;//獲取view的橫座標;
  CGFloat yBounds = view1.bounds.origin.y;//獲取view的縱座標;
  CGFloat widthBounds = view1.bounds.size.width;//獲取view的寬度;
  CGFloat heightBounds = view1.bounds.size.height;//獲取view的高度;
  
  
  //center 中心點;
  CGFloat xCenter = view1.center.x;
  CGFloat yCenter = view1.center.y;
  
  NSLog(@"frame   x=%.0f  y=%.0f   width=%.0f   height=%.0f",x,y,width,height);
  NSLog(@"bounds  x=%.0f  y=%.0f   width=%.0f   height=%.0f",xBounds,yBounds,widthBounds,heightBounds);
  NSLog(@"center   x=%0.f   y=%0.f",xCenter,yCenter);
  
  
  
 //座標是根據父檢視的位置來設定的,不會跨層;
  UIView *view2 = [[UIView alloc] init];
  view2.frame = CGRectMake(20, 20, 50, 50);
  view2.backgroundColor = [UIColor redColor];
  view2.tag = 101;//唯一標示值;
  [view1 addSubview:view2];
  
  UIView *view3 = [[UIView alloc] init];
  view3.frame = CGRectMake(100, 100, 50, 50);
  view3.backgroundColor = [UIColor redColor];
  view3.tag = 102;
  [view1 addSubview:view3];
  

  
  
  //獲取view1的父檢視;
  UIView *superView = view1.superview;
  superView.backgroundColor = [UIColor grayColor];
  
  
  
  //獲取view1的所有子檢視,返回的是陣列;
  NSArray *subViewArray = view1.subviews;
  
  for (UIView *subView in subViewArray) {
    if (subView.tag == 101) {
      subView.backgroundColor = [UIColor blackColor];
      
    } else {
      subView.backgroundColor = [UIColor whiteColor];
    }
  }
  
  
  
  //能獲取指定tag識別符號的View;
  UIView *v = [view1 viewWithTag:101];
  v.backgroundColor = [UIColor purpleColor];
  
}

@end

實現效果如下:

.


github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!

相關文章