iOS專案開發實戰——理解frame,bounds,center

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

      在iOS介面設計中,設定控制元件的大小往往會用到frame,bounds或者center。我們也同時可以來獲得控制元件的位置資訊。具體程式碼如下:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
  [super viewDidLoad];
  
  
  //檢視;
  UIView *view1 = [[UIView alloc] init];
  //位置大小;
  view1.frame = CGRectMake(20, 30, 100, 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是View邊框的位置與大小;
  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);
  
}

@end

輸出結果如下:

·


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


相關文章