ios - 以编程方式更新高度约束

标签 ios objective-c swift autolayout nslayoutconstraint

我是自动布局的新手。我已经从 xib 文件完成了我的所有项目,但现在我遇到了一个问题,我必须以编程方式更新 View 的高度。我在下面尝试过,但现在可以工作了。

[[self view] addConstraint:[NSLayoutConstraint constraintWithItem:loginContainer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:loginFrame.size.height]];

在控制台中显示

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>",
    "<NSLayoutConstraint:0x787da210 V:[UIView:0x790cdfb0(400)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x78724530 V:[UIView:0x790cdfb0(170)]>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

最佳答案

您需要修改现有约束上的常量,而不是添加新约束。

使用 IBOutlet 连接到 Interface Builder 中的约束:

@property (nonatomic, weak) NSLayoutConstraint *heightConstraint;

然后,当您需要以编程方式设置它时,只需在约束上设置常量属性:

heightConstraint.constant = 100;

如果在 Interface Builder 中无法访问 nib,请在代码中查找约束:

NSLayoutConstraint *heightConstraint;
for (NSLayoutConstraint *constraint in myView.constraints) {
    if (constraint.firstAttribute == NSLayoutAttributeHeight) {
        heightConstraint = constraint;
        break;
    }
}
heightConstraint.constant = 100;

在 Swift 中:

if let constraint = (myView.constraints.filter{$0.firstAttribute == .width}.first) {
            constraint.constant = 100.0
        }

关于ios - 以编程方式更新高度约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060373/

相关文章:

缩放 Paint 应用程序的 OpenGL ES 内容时 iPhone 像素失真

ios - 每次我按下 Swift 中的按钮时,带有图像名称的数组都会更改我的图像

swift - ARKit 拖动对象改变比例

ios - ARKit - 点击屏幕后物体粘在相机上

ios - 在 MapBox Android 和 iOS 上显示 GeoJSON

html - iOS 在服务器端 javascript 运行后解析 html

ios - 删除除最后一个以外的所有事件

iphone - Key-Value-Observation——寻找更优雅的解决方案来响应值的变化

objective-c - OS X 钥匙串(keychain) : 32 to 64 bit

ios - 当我们退出应用程序而不终止应用程序 Swift 4 时,弹出窗口不会重新出现