两个视图,一个在纵向下面,另一个在横向上使用布局约束

时间:2013-05-24 06:58:51

标签: iphone ios ios6 storyboard nslayoutconstraint

假设我有两个文本视图。 在肖像模式下,我希望这些在另一个下面。 在横向模式中,我希望这些是并排的

是否可以使用自动布局在故事板中使用布局约束来实现? 如果是,那怎么样? 如果没有,那么实现这一目标的另一个更好的解决方案是什么。

ios6是我的目标版本

3 个答案:

答案 0 :(得分:8)

以下是您在代码中的使用方法。

基本上你需要:

a)在NSLayoutConstraint的{​​{1}}中为给定方向配置相应的updateViewConstraints

b)界面旋转时调用UIViewController

下面是一个ViewController实现和UIView上带有辅助方法的类别。

[self.view setNeedsUpdateConstraints]

将它放在UIView + Constraints.h

@interface ConstraintsViewController ()

@property (nonatomic, weak) IBOutlet UIView  *upperOrLeftView, *lowerOrRightView;

@end


@implementation ConstraintsViewController

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
    [self.view setNeedsUpdateConstraints];
}

-(void)updateViewConstraints {
    [super updateViewConstraints];

    [self.view removeConstraintsRelatingToItems:@[self.upperOrLeftView,self.lowerOrRightView]];

    if(UIInterfaceOrientationIsPortrait(self.interfaceOrientation)) {
        [self.view constrainSubview:self.upperOrLeftView usingEdgeInsets:UIEdgeInsetsMake(0, 0, -1, 0)];
        [self.view constrainSubview:self.lowerOrRightView usingEdgeInsets:UIEdgeInsetsMake(-1, 0, 0, 0)];
        [self.view constrainSubviewsTopToBottom:@[self.upperOrLeftView, self.lowerOrRightView]];
    }
    else {
        [self.view constrainSubview:self.upperOrLeftView usingEdgeInsets:UIEdgeInsetsMake(0, 0, 0, -1)];
        [self.view constrainSubview:self.lowerOrRightView usingEdgeInsets:UIEdgeInsetsMake(0, -1, 0, 0)];
        [self.view constrainSubviewsLeftToRight:@[self.upperOrLeftView, self.lowerOrRightView]];
    }
}

@end

这是UIView + Constraints.m

@interface UIView (Constraints)

-(void)removeConstraintsRelatingToItems:(NSArray*)items;

-(void)constrainSubview:(UIView*)subview usingEdgeInsets:(UIEdgeInsets)insets;

-(void)constrainSubviewsLeftToRight:(NSArray*)subviews;

-(void)constrainSubviewsTopToBottom:(NSArray*)subviews;

@end

答案 1 :(得分:2)

在我看来,在多个方向上布局viewController视图的最佳方法是为每个方向创建几个视图。 Here我发现了这个:

“当您向故事板添加视图控制器时,它会带有一个视图。调用容器视图。向容器视图添加两个视图:纵向视图和横向视图。设置纵向视图的尺寸和使用尺寸检查器适当地进行横向视图。根据应用需要为纵向和横向视图添加按钮,更多视图,标签或其他内容。然后当方向更改时隐藏一个视图并显示另一个视图。“

答案 2 :(得分:0)

您只能使用Interface Builder来实现此类行为。您需要设置一些具有不同优先级的约束。

请参阅我对here主题的更详细解答。还有一个截屏视频和指向我创建的示例应用程序的链接。