如何以编程方式删除从故事板添加的约束?

Dha*_*mik 38 ios xcode-storyboard ios-autolayout

我用谷歌搜索但没有找到答案.所以我需要问一下.我有一个主屏幕.当用户登录时,它将显示一个视图,如下图所示 在此输入图像描述 现在,当用户退出并访问主页时,他将看到上面的布局,但没有中心框的布局.如果我将该布局设置为隐藏,则它现在显示如下. 在此输入图像描述

我想将第三个布局移到上面一点点以移除空白区域..

我使用故事板添加了约束.现在需要从编程中删除约束并添加一个约束,将布局设置为低于第一个布局.

Mru*_*nal 36

正如@Henit所提到的,您也可以为约束设置IBOutlet.

例如,

@property(weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;
Run Code Online (Sandbox Code Playgroud)

所以现在,您可以删除此约束,如下所示:

[myView removeConstraint: viewHeight];
Run Code Online (Sandbox Code Playgroud)

或者如果你想删除与你的视图相关的所有/多个约束,那么,

[myView removeConstraints: constraintsArrayHere]; // custom array of constraints references
[myView removeConstraints: [myView constraints]]; //all constraints
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用addConstraintaddConstraints方法以相同的方式添加新约束.

有关详细信息,请在此处查看 Apple文档.

希望这可以帮助.


Meg*_*ind 25

removeConstraints将来会被弃用.

您可以使用以下替代方法

viewHeight.active = NO;
Run Code Online (Sandbox Code Playgroud)


AXE*_*AXE 14

要扩展@ Megamind的答案:你可以使用的active属性NSLayoutConstraint.只需为这两种情况设置两种不同的约束,并根据登录状态仅激活其中一种情况.在InterfaceBuilder中,该active属性被奇怪地称为Installed:

登录约束注册约束

然后在你的代码之间切换两者:

- (void)setupRegistrationView
{        
    _loadingIndicatorTopConstraintLogin.active = NO;
    _loadingIndicatorTopConstraintRegister.active = YES;
}

- (void)setupLoginView
{        
    _loadingIndicatorTopConstraintLogin.active = YES;
    _loadingIndicatorTopConstraintRegister.active = NO;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,使用新的UIStackView可以为您的案例提供更优雅的解决方案,但这是另一个主题.


小智 11

当用户注销时,获取要隐藏的视图高度约束的IBOutlet.

@property(weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;
Run Code Online (Sandbox Code Playgroud)

有一个属性不变NSLayoutConstraint类.您需要在用户登录/注销时进行设置.

viewHeight.constant = isLoggedIn ? 30.0 : 0.0;
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助..


Ari*_*dar 9

Swift 4中

@IBOutlet weak var viewHeight: NSLayoutConstraint!
viewHeight.isActive = false    
Run Code Online (Sandbox Code Playgroud)

快乐编码:)


bla*_*acx 8

从iOS 10+开始,它非常简单,您可以简单地遍历视图的所有约束并停用它.如果您,例如想要查找和删除视图的高度约束,您可以执行以下操作:

for constraint in constraints {
    guard constraint.firstAnchor == heightAnchor else { continue }
    constraint.isActive = false
    break
}
Run Code Online (Sandbox Code Playgroud)

替代
它甚至是一个单行.如果你在视图中,你可以写:

constraints.first { $0.firstAnchor == heightAnchor }?.isActive = false
Run Code Online (Sandbox Code Playgroud)