在使用代碼編寫界面的時候會遇到一些重要屬性,其中frame和bounds這兩個屬性可能比較容易混淆code
bounds:表示該圖示在本地座標系統中的位置和大小,相對於本身it
frame:表示view在其父視圖座標系統中的位置和大小,相對於父視圖io
下面看例子class
@interface SecondViewController () @end @implementation SecondViewController - (void)viewDidLoad { [super viewDidLoad]; UIView *viewA = [[UIView alloc] init]; viewA.backgroundColor = [UIColor grayColor]; //設置viewA的frame屬性 viewA.frame = CGRectMake(0, 0, 300, 500); [self.view addSubview:viewA]; UIView *viewB = [[UIView alloc] init]; viewB.backgroundColor = UIColor.orangeColor; viewB.frame = CGRectMake(20, 80, 100, 100); [self.view addSubview:viewB]; NSLog(@"frame-x:%0.2f, frame-y:%.3f", viewB.frame.origin.x, viewB.frame.origin.y); NSLog(@"frame-width:%f, frame-height:%.1f", viewB.frame.size.width, viewB.frame.size.height); NSLog(@"bounds-x:%0.2f, bounds-y:%.2f", viewB.bounds.origin.x, viewB.bounds.origin.y); NSLog(@"bounds-width:%0.2f, bounds-height:%.2f", viewB.bounds.size.width, viewB.bounds.size.height); // 2018-06-28 14:12:22.333305+0800 UIViewDemo[79588:3484414] frame-x:20.00, frame-y:80.000 // 2018-06-28 14:12:22.333494+0800 UIViewDemo[79588:3484414] frame-width:100.000000, frame-height:100.0 // 2018-06-28 14:12:22.333595+0800 UIViewDemo[79588:3484414] bounds-x:0.00, bounds-y:0.00 // 2018-06-28 14:12:22.333730+0800 UIViewDemo[79588:3484414] bounds-width:100.00, bounds-height:100.00 // 上面結果還體現了佔位符問題,%f 默認取小數點後6位,%f.2表示取小數點後2位,%f0.2小國和%f.2同樣,%f.1 取小數點後一位 @end
frame-x:20.00, frame-y:80.000object
frame-width:100.000000, frame-height:100.0im
bounds-x:0.00, bounds-y:0.00view
bounds-width:100.00, bounds-height:100.00vi