【问题标题】:Programmatically change a Frame position以编程方式更改 Frame 位置
【发布时间】:2014-07-16 14:57:31
【问题描述】:

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

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

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


    }
    else
    {


    }
}

【问题讨论】:

    标签: xcode landscape-portrait programmatically-created


    【解决方案1】:
    - (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);
        }
     }
    

    【讨论】:

      【解决方案2】:

      您应该使用[self setFrame:CGRectMake(x, y, width, height)]; 中的代码 在这种情况下,self 将是您的 UIImageView, View or Button 的名称

      【讨论】:

        【解决方案3】:

        通常您应该在这种情况下使用 AutoLayout。 你可以在这里阅读:http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1

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

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

        - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
        

        【讨论】:

        • 我知道我应该使用自动布局,但我必须以编程方式创建 3 个元素,而且我无法在 Interface Builder 中创建它们,无论如何谢谢 :)
        • @user3789527 你可以在代码中添加约束:) NSLayoutConstraint *myConstraint =[NSLayoutConstraint constraintWithItem:mybutton attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:mylabel attribute:NSLayoutAttributeWidth multiplier:5 constant:0]; [superview addConstraint: myConstraint];
        • 该死的以为我不能以编程方式添加约束!非常感谢,这将为我节省大量编码:P
        【解决方案4】:

        您在 viewWillLayoutSubviews 中执行此操作。 通常,如果您需要做的只是相对于超级视图的边界进行帧更改,则不需要任何方向。

        【讨论】:

          猜你喜欢
          • 2019-07-16
          • 2012-01-12
          • 2011-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多