【问题标题】:Changing programmatic/VFL constraints on-the-fly即时更改程序化/VFL 约束
【发布时间】:2015-03-20 16:35:28
【问题描述】:

我正在手动将子视图添加到视图并使用约束对其进行定位...

UIView *superview = self.view;
UIView *subview = self.subview;

NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings(superview, subview);

[self.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[subview]-(0)-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]];
[self.superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[subview]-(0)-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]];

这会将我的子视图整齐地放置在超级视图中。但是,稍后我想在我的子视图(带有动画)周围应用一个边距,以便它被插入 100。所以实际上,我在视觉格式语言中的约束将是......

"H:|-(100)-[subview]-(100)-|"
"V:|-(100)-[subview]-(100)-|"

如何将变量附加到我的“边距”值,以便在子视图的两种显示类型之间进行转换?

【问题讨论】:

  • 据我所知,您只能更改常量值或约束的优先级。要更改间距,您必须删除旧约束,重新制作新约束,然后添加它们。

标签: ios objective-c iphone constraints nslayoutconstraint


【解决方案1】:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(0)-[subview]-(0)-|" options:NSLayoutFormatAlignAllBaseline metrics:nil views:viewsDictionary]

将返回一个数组,其中包含与指定顺序相同的约束,您可以在数组中查找它,然后更改其常量值。

但我认为最简单的方法是像这样创建对它的引用(您可以将其存储在内部变量或属性中):

NSLayoutConstraint* space = [NSLayoutConstraint constraintWithItem:self.button1 attribute:NSLayoutAttributeRight
                  relatedBy:NSLayoutRelationEqual toItem:self.button2
                  attribute:NSLayoutAttributeLeft multiplier:1.0 constant:12.0];

并像这样添加它:

[self.view addConstraints:@[space]];

然后您可以将 space.constant 更改为某个值。并像这样对其进行动画处理:

[UIView animateWithDuration:1.0 animations:^{
 // Make all constraint changes here
 [self.view layoutIfNeeded];}];

其他方法是删除所有约束并添加具有更新值的 VFL 约束,然后如上所述在动画块内执行 layoutIfNeeded。

【讨论】:

  • 谢谢。辛苦了!
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 2015-02-12
  • 2020-05-30
  • 2023-03-04
  • 2016-06-11
  • 1970-01-01
  • 2015-08-24
  • 2022-01-01
相关资源
最近更新 更多