經??吹竭@種說法,frame是基于父控件的,bounds是基于自身坐標的。然而,這個自身坐標是什么?bounds這個屬性存在的意義是什么呢?bounds的x和y值真的永遠是0嗎?
經過查閱資料,我看到這樣一種說法:一個控件,擁有其展示部分和內容部分。其展示部分是有限大的,固定坐標固定大小,而其內容部分是無限大的。就像一個電視機以及其播放的電影(這個比喻不太恰當,是我強行比喻的),電視機用于放映電影的屏幕(控件的展示部分)是固定位置固定大小的,然而電影的世界(控件的內容部分)是無限大的,我們只能展示這個無限的內容的有限部分。
github上的Demo鏈接
Demo演示bounds
先展示下效果圖
我設置了兩個view,一個是紅色的背景view,紅色view里嵌套了一個小的藍色的view。我給紅色view添加了點擊手勢,點擊紅色view,讓紅色view bounds.origin.y += 5;,并打印bounds的值。結果顯示,bounds的y值確實增加了,而實際效果是,藍色小色塊在不斷移動。
其實,frame設置的是其展示區域,就像電視機的顯示屏。而bounds設置的是其內容區域,就像電視機放映的電影中那個廣闊的世界一樣。對于這部分的理解,我想結合scrollView會更容易些。scrollView的frame設置的僅僅只是scrollView的展示界面,而其滑動區域需要設置contentSize屬性。
- (void)viewDidLoad { [super viewDidLoad]; // 紅色的背景view UIView *view = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]; view.backgroundColor = [UIColor redColor]; [self.view addSubview:view]; // 單擊手勢 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewClick:)]; [tap setNumberOfTouchesRequired:1]; [view addGestureRecognizer:tap]; // 藍色的子view UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 190, 10, 10)]; subView.backgroundColor = [UIColor blueColor]; [view addSubview:subView];}- (void)viewClick:(UITapGestureRecognizer *)gesture{ // 獲取紅色view UIView *view = gesture.view; // 修改bounds的值 CGRect bounds = view.bounds; bounds.origin.y += 5; view.bounds = bounds; // 展示bounds的值 NSLog(@"bounds:%@",NSStringFromCGRect(view.bounds));}
關于修改bounds后,其內容的移動規律,我是這樣理解的。我們都知道,左上角是(0,0),右下角方向移動,x和y都是增加的。而對于bounds,由于一個控件的展示部分被frame固定了,不可以隨意移動。而在上面的例子中,y是自增的,那么控件應該相對于內容部分向下移動才對(設置frame是相對于父控件移動,那么設置bounds就是針對自身的內容區域移動)。而控件是不能移動的,所以能移動的就是內容區域了。內容區域相對控件向相反的方向移動,也就是向上移動了。
仿寫UIScrollView的部分效果
仿寫思路:scrollView的滑動效果,我們可以通過添加滑動手勢實現。scrollView的內容滾動,我們可以通過修改scrollView的bounds來實現。
效果圖
代碼
- (void)viewDidLoad { [super viewDidLoad]; // 仿scrollView UIView *myScrollView = [[UIView alloc] initWithFrame:self.view.bounds]; myScrollView.backgroundColor = [UIColor redColor]; [self.view addSubview:myScrollView]; // 滑動手勢 UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGes:)]; [myScrollView addGestureRecognizer:pan]; // scrollView的內容 UIView *blueView = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 10, 10)]; blueView.backgroundColor = [UIColor blueColor]; [myScrollView addSubview:blueView];}- (void)panGes:(UIPanGestureRecognizer *)gesture{ UIView *myScrollView = gesture.view; // 獲取滑動的位移量 CGPoint transPoint = [gesture translationInView:myScrollView]; NSLog(@"%@",NSStringFromCGPoint(transPoint)); // 這里總感覺寫錯了,我腦子笨,有點繞不過來了。頭疼 CGRect bounds = myScrollView.bounds; bounds.origin.x -= transPoint.x; bounds.origin.y -= transPoint.y; myScrollView.bounds = bounds; // 復位 [gesture setTranslation:CGPointZero inView:myScrollView];}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答