用autolayout如何在横竖屏切换情况下改变控件的位置

来源:互联网 发布:手机汽车美容软件 编辑:程序博客网 时间:2024/06/08 19:47
在IB中,你用的autolayout来设置控件的位置和大小,你有一个需求,有一个imageView,水平居中,竖屏时距离top 280,但横屏时只有180,需要往上移一下。这怎么实现呢,好像在IB中没法设置他的动态距离吧?(如果哪位知道,请告诉我)

IB中不能设置,只好在代码中设置了。因为每次转屏时都会调用viewWillLayoutSubviews,所以在这个方法里设置就可以,具体方法是:


-(void)viewWillLayoutSubviews

{

    if (constraint) {

        [self.viewremoveConstraint:constraint];

    }

    if ([UIApplicationsharedApplication].statusBarOrientation ==UIDeviceOrientationPortrait || [UIApplicationsharedApplication].statusBarOrientation ==UIDeviceOrientationPortraitUpsideDown)

    {

       constraint = [

                      NSLayoutConstraint

                      constraintWithItem:self.view

                      attribute:NSLayoutAttributeTop

                      relatedBy:NSLayoutRelationEqual

                      toItem:self.backgroundImage

                      attribute:NSLayoutAttributeTop

                      multiplier:1.0f

                      constant:-280.0f

                      ];

    }

    else

    {

        constraint = [

                      NSLayoutConstraint

                      constraintWithItem:self.view

                      attribute:NSLayoutAttributeTop

                      relatedBy:NSLayoutRelationEqual

                      toItem:self.backgroundImage

                      attribute:NSLayoutAttributeTop

                      multiplier:1.0f

                      constant:-200.0f

                      ];

        

    }

    [self.viewaddConstraint:constraint];

}


从上面的代码中你就可以看出,做法就是判断是横屏还是竖屏,然后给self.view(也就是根view)加一个约束,距离imageView 280。
当转屏时,就会调用这个方法,然后重新设置imageview的位置,从而达到了需求。
0 0
原创粉丝点击