iOS-bounds、frame、center详解

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];
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容