UIStoryboard如何以编程方式替换约束?

2023-11-24

我在故事板中放置了一个视图控制器,并启用了自动布局,并且正在寻找一种方法来更改约束,以允许我的视图旋转为横向并重新排列屏幕上的按钮。当我尝试下面的代码时,我收到大约两打“无法满足约束,破坏约束......”的消息,我无法真正解码。

有没有办法用我以编程方式指定的约束动态替换故事板中的约束?我想完全覆盖我在故事板中定义的按钮布局。

-(void)updateViewConstraints
{
    [super updateViewConstraints];

    self.loginButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.getStartedButton.translatesAutoresizingMaskIntoConstraints = NO;
    self.takeTourButton.translatesAutoresizingMaskIntoConstraints = NO;



    [self.loginButton removeConstraints:self.loginButton.constraints];
    [self.getStartedButton removeConstraints:self.getStartedButton.constraints];
    [self.takeTourButton removeConstraints:self.takeTourButton.constraints];


    one = self.loginButton;
    two = self.getStartedButton;
    three = self.takeTourButton;


    NSDictionary *metrics = @{@"height":@50.0,@"width":@100.0,@"leftSpacing":@110.0};
    NSDictionary *views = NSDictionaryOfVariableBindings(one,two,three);

    [self.view removeConstraints:activeTestLabelConstraints];
    [activeTestLabelConstraints removeAllObjects];

    if(isRotatingToLandscape)
    {

        [self registerConstraintsWithVisualFormat:@"|-[one(two)]-[two(three)]-[three]-|" options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom metrics:metrics views:views];
        [self registerConstraintsWithVisualFormat:@"V:[one(height)]-|" options:0 metrics:metrics views:views];

    }else
    {

        [self registerConstraintsWithVisualFormat:@"|-leftSpacing-[one(width)]" options:0 metrics:metrics views:views];
        [self registerConstraintsWithVisualFormat:@"[two(width)]" options:0 metrics:metrics views:views];
        [self registerConstraintsWithVisualFormat:@"[three(width)]" options:0 metrics:metrics views:views];
        [self registerConstraintsWithVisualFormat:@"V:[one(height)]-[two(75)]-[three(100)]-|" options:NSLayoutFormatAlignAllCenterX metrics:metrics views:views];
    }


}

更新了罗布的答案,这是我使用的删除约束的方法

-(void)removeConstraintForView:(UIView*)viewToModify
{

    UIView* temp = viewToModify;
    [temp removeFromSuperview];
    [self.view addSubview:temp];

}

听起来您只想删除视图上的所有约束。由于视图上的约束通常由视图的祖先保留,因此如何轻松删除所有约束并不明显。但这实际上很容易。

从视图层次结构中删除视图会删除该视图与其外部其他视图之间的任何约束。因此,只需从其超级视图中删除您的视图,然后将其添加回来:

// Remove constraints betwixt someView and non-descendants of someView.
UIView *superview = someView.superview;
[someView removeFromSuperview];
[superview addSubview:someView];

如果两者之间有任何限制someView及其后代,这些限制可能由someView本身(但不能由任何后代持有)someView)。如果您还想删除这些限制,可以直接这样做:

// Remove any remaining constraints betwixt someView and its descendants.
[someView removeConstraints:[someView constraints]];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

UIStoryboard如何以编程方式替换约束? 的相关文章

随机推荐