ios - 动态更改程序/VFL 约束

标签 ios objective-c iphone constraints nslayoutconstraint

我正在手动将 subview 添加到 View 中,并使用约束来定位它...

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]];

这将我的 subview 整齐地放置在 super View 中。然而,稍后我想在我的 subview (带动画)周围应用边距,以便它插入 100。所以实际上,我对视觉格式语言的约束将是...

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

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

最佳答案

[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 约束,然后如上所述在动画 block 内执行 layoutIfNeeded。

关于ios - 动态更改程序/VFL 约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29171555/

相关文章:

ios - 如何使用自定义单元格中的按钮获取自定义 UITableViewCell 的行,该按钮将发送到 deleteRowsAtIndexPaths

ios - 使用旧版 Swift 语言版本 - Xcode 8.2

iphone - 如何转换字符串-> pdf

iphone - 单例的后果

iphone - 如何在 UIImageView 上制作可点击的 UIButton?

ios - GPUImage2 无法实时循环过滤器

ios - Firebase、iOS 和 Swift 入门

ios - 当 block 从 swift 转移到 Objective-C 时出现内存问题

objective-c - 如何在UIWebView中跳转pdf页面?

iphone - 如何获取替换开发证书的 p12 文件?