gpt4 book ai didi

objective-c - 通过代码添加和设置 NSLayoutConstraint

转载 作者:太空狗 更新时间:2023-10-30 03:29:04 27 4
gpt4 key购买 nike

我在使用 NSLayoutConstraint 时遇到了一些问题。

如果我尝试使用 setConstant: 方法更改 constant,NSLayoutConstraint 会给我一个异常(exception)。我只有在通过代码添加高度约束时才会遇到这个问题。

首先,我得到了这样的高度限制:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"firstAttribute = %d", NSLayoutAttributeWidth];
NSArray *filteredArray = [[self constraints] filteredArrayUsingPredicate:predicate];
return filteredArray[0];

这给了我正确的约束。我有一个 NSTextField 子类,它可以完美地工作。约束在 Interface Builder 中设置,我可以设置和更改常量。

现在我有一个 View ,我在运行时添加不同的 subview 。这些 subview 位于自己的 NIB 中,这意味着我无法固定它们的宽度和高度。所以我想我会在将 View 添加到父 View 后立即添加约束。这是在 viewDidMoveToSuperview 中执行的。

// Pin Width & Height
[self addConstraint:[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:self.frame.size.width]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0f
constant:self.frame.size.height]];

添加了约束,我可以用 NSLog 确认这一点。

"<NSLayoutConstraint:0x100605cc0 H:[ITControlPanelChildView:0x100616eb0(269)]>",
"<NSLayoutConstraint:0x100614410 V:[ITControlPanelChildView:0x100616eb0(317)]>"

现在,最后,当我尝试使用 [constraint setConstant:somethingDifferent]; 更改约束时,我得到以下异常:

Unable to simultaneously satisfy constraints:
(
"<NSLayoutConstraint:0x10192fcb0 V:[ITControlPanelChildView:0x10192e4f0(100)]>",
"<NSAutoresizingMaskLayoutConstraint:0x10053ff10 h=--& v=&-- V:[ITControlPanelChildView:0x10192e4f0(317)]>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x10192fcb0 V:[ITControlPanelChildView:0x10192e4f0(100)]>

这正是我试图改变的约束。谁能向我解释为什么会这样?


编辑

我刚刚读到 NSAutoresizingMaskLayoutConstraint 是自动添加的,如果您设置 [self setTranslatesAutoresizingMaskIntoConstraints:NO];,您可以禁用它。

如果我禁用它,它会起作用。

如果我可以访问创建的 NSAutoresizingMaskLayoutConstraint 会更好。有谁知道这是如何工作的?

最佳答案

正如您未包含的日志消息的其余部分所示,您有不想要或不需要的自动调整大小约束。

您可以在添加 subview 时删除这些。在上面使用的方法中,只需添加以下行:

self.translatesAutoresizingMaskIntoConstraints = NO;

如果您在单独的 nib 中创建 View ,那么它的大小从何而来?它不是已经有大小限制,您可以创建导出吗?

关于objective-c - 通过代码添加和设置 NSLayoutConstraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13958037/

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