gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:48:57 24 4
gpt4 key购买 nike

我在启用了自动布局的 Storyboard中布置了一个 View Controller ,我正在寻找一种方法来更改约束以允许我的 View 旋转成横向并重新排列屏幕上的按钮。当我尝试下面的代码时,我收到大约两打“无法满足约束、破坏约束……”我无法真正解码的消息。

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

-(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];
}


}

更新了 Rob 的回答,这是我使用的删除约束的方法

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

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

}

最佳答案

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

从 View 层次结构中删除一个 View 会删除该 View 与其外部其他 View 之间的任何约束。因此,只需从其父 View 中删除您的 View ,然后再将其添加回去:

// 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]];

关于objective-c - UIStoryboard 如何以编程方式替换约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17867125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com