bounds、frame、center
<p>
frame: 該view在父view坐標系統中的位置和大小。(參照點是,父親的坐標系統)
</p>
<p>
bounds:該view在本地坐標系統中的位置和大小。(參照點是,本地坐標系統,就相當于ViewB自己的坐標系統,以0,0點為初始值)
</p>
<p>
center:該view的中心點在父view坐標系統中的位置和大小。(參照點是,父親的坐標系統)
</p>
<p> 如圖: </p>
frameAndBounds
<p>
主要是每一個視圖都由兩套坐標系統構成:1、父親坐標系統 2、本地坐標系統。
<ul>
<li> 一個view,其在父控件中的顯示位置由frame和父控件的本地坐標決定,frame和父控件本地坐標不變則其位置不變 </li>
<li> 如果這個view的bounds坐標改變,而frame不變則view相對于父控件位置還是原來位置,而結果是view的本地坐標原點改變(本地坐標原點是抽象的參照點) </li>
<li> 一個view,其bounds的坐標是其左上角點參照于其自身本地坐標系的坐標值,默認職位(0,0) </li>
<li> bounds的y增大100,最終顯示不是view向下移動100,而是其本地坐標系相對向上移動100,也即參照其本地坐標系的子控件跟隨著向上移動100 </li>
</ul>
</p>
總結:bounds的改變可以理解為內容視圖的位置改變,所有子視圖都是當前視圖的內容視圖,當前視圖的自視圖的位置隨之改變,而視圖本身不會改變。
例子:
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor=[UIColor redColor];
CGRect bounds=self.view.bounds;
bounds=CGRectMake(-100, -100, bounds.size.width, bounds.size.height);
self.view.bounds=bounds;
UIView *subView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
subView.backgroundColor=[UIColor grayColor];
[self.view addSubview:subView];
}
bounds
延伸
<p>
系統實現UIScrollView和UITableView或者UICollectionView也是通過改變bounds實現內部內容滾動的,在此僅分析系統UIScrollView的實現
</p>
例子:
#import "ViewController.h"
@interface ViewController ()<UIScrollViewDelegate>
@property (nonatomic, strong) UIView *scrollView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 模仿系統控件 => 怎么去使用 => 滾動scrollView,其實本質滾動內容 => 改bounds => 驗證
// => 手指往上拖動,bounds y++ ,內容才會往上走
UIView *scrollView = [[UIView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:scrollView];
_scrollView = scrollView;
// 添加Pan手勢
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
[scrollView addGestureRecognizer:pan];
UISwitch *switchView = [[UISwitch alloc] init];
[scrollView addSubview:switchView];
_scrollView=scrollView;
}
- (void)pan:(UIPanGestureRecognizer *)pan
{
// 獲取手指的偏移量
CGPoint transP = [pan translationInView:pan.view];
NSLog(@"%f",transP.y);
// 修改bounds
CGRect bounds = _scrollView.bounds;
bounds.origin.y -= transP.y;
_scrollView.bounds = bounds;
// 復位
[pan setTranslation:CGPointZero inView:pan.view];
}