[英]How to center two views using view.frame and view.center
我想在這里做一些非常基本的事情。 我正在使用基於塊的UIView動畫將當前離開屏幕的子視圖帶到當前視圖的中心。 顯然sp.view.frame = self.view.center
行是這里的問題。 最后,我該怎么做我想要的?
[UIView animateWithDuration:1 delay:0
options:UIViewAnimationOptionCurveLinear
animations:^{
sp.view.frame = self.view.center;
}
謝謝!
首先, sp.view.frame
返回一個CGRect
而self.view.center
返回一個CGPoint
。 這兩個不是同一類型,因此不能設置為另一個。 ASssuming你想設置的中心sp.view
為中心self.view
,你可以做,在以下兩種方法之一:
sp.view.center = self.view.center;
要么
[sp.view setCenter:self.view.center];
self.view.center
是一個CGPoint結構。
sp.view.frame
是一個CGRect結構。
您不能將CGPoint分配給CGRect,因為類型不同。
如果要居中子視圖,使用這樣的事情,假設sp.view
是一個子視圖self.view
:
sp.view.frame = CGRectMake
(
( self.view.frame.size.width / ( CGFloat )2 ) - ( sp.view.frame.size.width / ( CGFloat )2 ),
( self.view.frame.size.height / ( CGFloat )2 ) - ( sp.view.frame.size.height / ( CGFloat )2 ),
sp.view.frame.size.width,
sp.view.frame.size.height
);
編輯
或者諾亞建議:
sp.view.center = CGPointMake( self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
謝謝諾亞,順便說一下......
可以像這樣添加一個宏
#define countmid(X,Y) (float) (XY)/2
然后在代碼中使用它
float Center = countmid(VIEW.frame.size.width,SUB.frame.size.width);
將SUB視圖放在VIEW的水平中心
垂直中心也是如此,只需使用高度和寬度
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.