Xcode 以编程方式更改帧位置

Xcode 以编程方式更改帧位置,xcode,landscape-portrait,programmatically-created,Xcode,Landscape Portrait,Programmatically Created,我以编程方式创建了一个视图、一个UIImageView和一个按钮。问题是,如果设备从纵向切换到横向,我需要更新它们的位置,我该怎么做 这应该是检查设备是否处于纵向或横向模式的代码 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { if (toInterfaceOrientat

我以编程方式创建了一个视图、一个UIImageView和一个按钮。问题是,如果设备从纵向切换到横向,我需要更新它们的位置,我该怎么做

这应该是检查设备是否处于纵向或横向模式的代码

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {


    }
    else
    {


    }
}

您应该沿着
[self-setFrame:CGRectMake(x,y,width,height)]的行使用代码

在这种情况下,
self
将是您的
ui图像视图、视图或按钮的名称

通常情况下,您应该使用自动布局。
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
    {
//change the frame for sideways direction
btn.frame=CGRectMake(x,y,width,height);
imgView.frame=CGRectMake(x,y,width,height);
view.frame=CGRectMake(x,y,width,height);
    }
else
    {
//change the frame for up/down
btn.frame=CGRectMake(x,y,width,height);
imgView.frame=CGRectMake(x,y,width,height);
view.frame=CGRectMake(x,y,width,height);
    }
 }
您可以在此处阅读:

如果你想要特别的东西,你可以用

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration


您可以在ViewWillLayoutSubView中执行此操作。
通常情况下,如果只需更改superview边界的框架,则不需要具有任何方向。

我知道我应该使用autolayout,但我必须以编程方式创建3个元素,而我无法在Interface Builder中创建它们,无论如何,谢谢:)@user3789527您可以在代码中添加构造:)NSLayoutConstraint*myConstraint=[NSLayoutConstraint constraintWithItem:mybutton属性:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:mylabel属性:NSLayoutAttributeWidth乘数:5常量:0];[superview addConstraint:myConstraint];该死的,我以为我无法以编程方式添加约束!非常感谢,这将为我节省大量的编码:P
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation