Bounds,Frame根本區別(利用Bounds繼承View實現ScrollView基本功能)

分類:技術 時間:2016-10-04

對于初學者來說Bounds簡直太簡單了,就是x,y為0的Frame.

當時我也是這么認為的.

可是一直不明白,既然有了Frame,蘋果為什么還要設計出Bounds呢,既然x,y都是0的話,直接用Size不可以嗎?

存在就是有道理的,Bounds和Frame有根本的區別的(而且很大).

本文介紹Bounds和Frame的根本區別

并利用Bounds,繼承View實現ScrollView滾動功能.

  • 首先來區分frame和bounds的區別

    我們都知道frame有origin和size
    origin決定自己的位置
    size決定自己的大小
    但是,位置是相對于父控件來說的(父控件左上角為坐標原點0,0)
    那么bounds的origin和size,就是相對于自己來說的(自己的左上角為坐標原點0,0)
    確切的說,是自己的子控件的位置相對于自己來說的.
  • 一個小Demo:

    定義一個紅色View處于控制器View的最低端:

初始狀態.png

如果在代碼中讓frame.origin.y 減少20

紅色View會帶著自己的子控件一起向上移動20(地球人都知道)

如果讓bounds.origin.y 增加20呢

是的,他的子控件位置變化了(自己位置沒有變):

bounds--.png

但是奇怪的是子控件的位置是向下移動的

說明bounds和frame的y方向是相反的,

如果讓bounds.origin.y 增加20:

bounds .png

果然,子控件相對于自己向上了20(自己沒有動)

  • 結論:

    每個控件都有自己的frame和bounds

    frame決定自己在父控件(爸爸)中的位置和大小

    bounds決定子控件(兒子)在自己內部的位置和大小

    多么對稱的設計......

  • 利用Bounds,繼承View實現ScrollView滾動功能.

    (Demo地址: https://github.com/huberyhx/HXScrollView.git )

    根據我們對bounds的研究

    改變bounds,就是改變子控件在自己內部的大小

    這貌似就是ScrollView啊(其實就是)

    接下來就獲得手指在屏幕拖動的距離來改變子控件的bounds,實現ScrollView的滾動:

    首先創建手勢:

    UIView *scrollView = [[UIView alloc] initWithFrame:self.view.bounds];
      [self.view addSubview:scrollView];
      self.scrollView = scrollView;
    
      // 添加Pan手勢
      UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
      [scrollView addGestureRecognizer:pan];
    
      //添加一個子控件來觀察子控件的位置
      UISwitch *switchView = [[UISwitch alloc] init];
      [scrollView addSubview:switchView];

    然后在手勢方法中改變view的bounds:

    -(void)pan:(UIPanGestureRecognizer *)pan
    {
      // 獲取手指的偏移量
      CGPoint transP = [pan translationInView:pan.view];
    
      // 修改bounds
      CGRect bounds = _scrollView.bounds;
      bounds.origin.y -= transP.y;
      _scrollView.bounds = bounds;
      //pan手勢的偏移量要記得復位(拿到相對于上一次的偏移量)
      [pan setTranslation:CGPointZero inView:pan.view];
    }

    完事,Demo地址在上面↑

    該Demo并沒有ScrollView的回彈效果(有時間補上)


Tags: ScrollView

文章來源:http://www.jianshu.com/p/6399af48b5c8


ads
ads

相關文章
ads

相關文章

ad