ios - 为什么 Interface Builder 不能为约束设置负倍数,即使 [NSLayoutConstraint constraintWithItem :] can?

标签 ios objective-c xcode

我有一个 iOS 9 和 10 应用程序,它在窗口底部有一个小“托盘” UIView,可以滑入和滑出以显示(或隐藏)某些控件。默认情况下,托盘完全显示(“滑出”),因此用户可以看到所有内容。最右边有一个按钮,他们可以点击该按钮使托盘“滑入”到左侧,这样托盘大部分都被隐藏了,因为它现在在左侧屏幕外。 (最右边的 20 个点是用户可以点击以滑入/滑出的“拇指”,因此拇指是托盘滑入时唯一保持可见的部分。)

我想这样做的方法是通过 Interface Builder 定义两个不同的约束,我只是简单地切换它们,以便一次只有一个处于事件状态。例如,这两个约束可能是:

托盘输出约束:

trayView.leading = (superview.leading * 1) + 0 // result == 0



托盘约束:

trayView.leading = (superview.trailing * -1) + 20 // result == -300 (for example)



事实证明,我可以像这样以编程方式为 trayInConstraint 创建约束(编辑:展开以显示我如何禁用 Storyboard 的默认约束并添加我的新约束):
// Disable the default constraint (in the storyboard)
[[self trayTripOutLeadingConstraint] setActive:NO];

// Create the new constraint (add to an array by itself)
NSLayoutConstraint *newConstraint = [NSLayoutConstraint constraintWithItem:(id)trayView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:(id)[trayView superview] attribute:NSLayoutAttributeTrailing multiplier:-1 constant:20];
NSArray *newTrayConstraintsArray = [[NSArray alloc] initWithObjects:newConstraint, nil];

// Remove any existing constraints array and use the new one    
[[self view] removeConstraints:[self tripTrayConstraints]];
[self setTripTrayConstraints:newTrayConstraintsArray];
[[self view] addConstraints:newTrayConstraintsArray];

但是如果我尝试在 Interface Builder 中创建它,我不能将乘数设置为 1.0 以外的任何值。 (键入任何其他值只会强制它重置为“1”。)

我在 Apple 文档中看到 https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/AutolayoutPG/AnatomyofaConstraint.html :

You cannot use a nonidentity multiplier (a value other than 1.0) with location attributes.



但是为什么我可以在代码中创建它而不是 IB?

(除了可能对其他人有用的无关之外:我还想创建一个约束,其中倍数为 0,但无法以编程方式或在 IB 中执行此操作。我发现我可以解决无法使用“0.0”作为乘数改为使用非常小的值,例如 0.000001。)

最佳答案

选择 "Reverse First And Second Item"并重新输入乘数的绝对值 => 这样(通过切换第一项和第二项)乘数的行为就像是负数。

Reverse First And Second Item

第一项:View.Leading
第二项:Superview.Trailing

normal

第一项:Superview.Trailing
第二项:View.Leading

reversed

关于ios - 为什么 Interface Builder 不能为约束设置负倍数,即使 [NSLayoutConstraint constraintWithItem :] can?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529761/

相关文章:

objective-c - FSMountServerVolumeSync 参数 objective-c

ios - iOS 中如何避免回调 hell ?

ios - 如何检查我是否在 UI 测试中将应用留在测试中?

objective-c - 未调用 touchesShouldCancelInContentView

objective-c - 为 REST API 开发 iOS SDK

ios - 如何为不同版本的 Xcode 编写条件语句

ios - 带有 NSLayoutAttributeTrailing 的 NSLayoutConstraints 不符合预期

objective-c - 你可以继承 objc 中编译时不可用的类吗?

iphone - UISegmentedControl - 在 Interface Builder 中改变高度

ios - 使用 tesseract 识别车牌