標籤:
搞iOS開發的童鞋基本都會用過UIView,那他的bounds和frame兩個屬性也不會陌生,那這兩個有什麼實質性的區別呢?
先看到下面的代碼你肯定就明白了一些:
-(CGRect)frame{
returnCGRectMake(self.frame.origin.x,self.frame.origin.y,self.frame.size.width,self.frame.size.height);
}
-(CGRect)bounds{
returnCGRectMake(0,0,self.frame.size.width,self.frame.size.height);
}
很明顯,bounds的原點是(0,0)點,而frame的原點卻是任意的。
再來看張圖,你就會更清楚了。
基本概念:
frame:該view在父view座標系統中的位置和大小。(參照點是,父親的座標系統) bounds:該view在本地座標系統中的位置和大小。(參照點是,本地座標系統) center:該view的中心點在父view座標系統中的位置和大小。(參照電是,父親的座標系統)實際上只有bounds和center兩個屬性。frame是為了方便直觀多加的屬性。所以修改了一個可能會影響到其他屬性。文檔中如下說: Although you can set the values of theseproperties independently, setting the value for one changes theothers in the following ways: When you set the frame property, the sizeof the bounds property is set to match the size of theframeproperty. The center property is also adjusted to match thecenter point of the new frame. When you set the center property, theorigin of the frame changes accordingly. When you set the size of the boundsrectangle, the size of the frame rectangle changes to match。
前兩個很明顯,最後一個bounds稍微有點費解。這裡一定要順便說下本地座標系統:每個view都有一個本地座標系統。這個座標系統作用比較重要,比如觸摸的回呼函數中的UITouch裡面的>座標值都是參照這個本地座標系統的座標。當然bounds這個屬性也是參照這個本地座標系統來的。其實本地座標系統的關鍵就是要知道的它的原點(0,0)在什麼位置(這個位置又是相對於上層的view的本地座標系統而言的,當然最上面的一層view就是window它的本地座標系統原點就是螢幕的左上方了)。通過修改view的bounds屬性可以修改本地座標系統的原點位置。
修改bounds測試結果: bounds (0,0,100,100) -->(0,0,200,200) 本地座標系統原點往左往上分別50。center不變,效果是按照中心放大view bounds(0,0,100,100) -->(100,100,100,100)本地座標系統原點往左往上分別100。center不變,沒有可視效果變化(但是本地座標系統的原點已經改變) 結論:
bounds屬性影響到本地座標系統的原點。需要注意
UIView 中bounds和frame的差別