ios 如何使用 view.frame 和 view.center 将两个视图居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7394288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:29:08  来源:igfitidea点击:

How to center two views using view.frame and view.center

iosanimation

提问by SimplyKiwi

I am trying to do something pretty basic here. I am using a block-based UIView animation to bring the subview that is currently off the screen to the current view's center. Obviously the sp.view.frame = self.view.centerline is the issue here. In the end, how do I do what I want?

我正在尝试在这里做一些非常基本的事情。我正在使用基于块的 UIView 动画将当前不在屏幕上的子视图带到当前视图的中心。显然,这sp.view.frame = self.view.center条线是这里的问题。最后,我该怎么做我想做的事?

[UIView animateWithDuration:1 delay:0
                    options:UIViewAnimationOptionCurveLinear
                 animations:^{
    sp.view.frame = self.view.center;        
}

Thanks!

谢谢!

回答by PengOne

First, sp.view.framereturns a CGRectwhereas self.view.centerreturns a CGPoint. The two are not the same type and so one cannot be set to the other. ASssuming you wish to set the center of sp.viewto be the center of self.view, you can do that in one of two ways:

首先,sp.view.frame返回 aCGRectself.view.center返回 a CGPoint。两者不是同一类型,因此不能将其设置为另一种。假设您希望将 的中心设置sp.view为 的中心self.view,您可以通过以下两种方式之一进行操作:

sp.view.center = self.view.center;

or

或者

[sp.view setCenter:self.view.center];

回答by Macmade

self.view.center

is a CGPoint struct.

是一个 CGPoint 结构。

sp.view.frame

is a CGRect struct.

是一个 CGRect 结构。

You can't assign a CGPoint to a CGRect, as the types are not the same.

您不能将 CGPoint 分配给 CGRect,因为类型不同。

If you want to center a subview, use something like this, assuming sp.viewis a subview of self.view:

如果要使子视图居中,请使用以下内容,假设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
);

EDIT

编辑

Or as Noah suggested:

或者像诺亚建议的那样:

sp.view.center = CGPointMake( self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);

Thanks Noah, btw...

谢谢诺亚,顺便说一句...

回答by ETech

It is possible to add a macro like this
#define countmid(X,Y) (float) (X-Y)/2
and then use it in code as
float Center = countmid(VIEW.frame.size.width,SUB.frame.size.width);
to place your SUB view at horizontal center of VIEW
The same for Vertical center, just use height against width

可以添加这样的宏
#define countmid(X,Y) (float) (X-Y)/2
,然后在代码中使用它,
float Center = countmid(VIEW.frame.size.width,SUB.frame.size.width);
将您的 SUB 视图放置在 VIEW
的水平中心对于垂直中心,只需使用高度与宽度