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

Sim*_*iwi 9 animation ios

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

[UIView animateWithDuration:1 delay:0
                    options:UIViewAnimationOptionCurveLinear
                 animations:^{
    sp.view.frame = self.view.center;        
}
Run Code Online (Sandbox Code Playgroud)

谢谢!

Pen*_*One 16

首先,sp.view.frame返回a CGRectself.view.center返回a CGPoint.这两个不是同一类型,因此不能设置为另一个.ASssuming你想设置的中心sp.view是中心self.view,你可以做,在以下两种方法之一:

sp.view.center = self.view.center;
Run Code Online (Sandbox Code Playgroud)

要么

[sp.view setCenter:self.view.center];
Run Code Online (Sandbox Code Playgroud)


Mac*_*ade 9

self.view.center
Run Code Online (Sandbox Code Playgroud)

是一个CGPoint结构.

sp.view.frame
Run Code Online (Sandbox Code Playgroud)

是一个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
);
Run Code Online (Sandbox Code Playgroud)

编辑

或者诺亚建议:

sp.view.center = CGPointMake( self.view.bounds.size.width / 2, self.view.bounds.size.height / 2);
Run Code Online (Sandbox Code Playgroud)

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

  • 更近,但仍然关闭.这会将子视图的左上角放在其超视图的中心位置.可能最好只使用`subview.center = CGPointMake(superview.bounds.size.width/2,superview.bounds.size.height/2) (2认同)