在 Swift 中枚举视图的 NSLayoutConstraints? [英] Enumerating a view's NSLayoutConstraints in Swift?
问题描述
[self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
if ((constraint.firstItem == view) && (constraint.firstAttribute == NSLayoutAttributeTop)) {
constraint.constant = -200;
}
}];
在 Objective-C 中,我将能够枚举视图的约束并相应地调整约束,但在 Swift 中我很难弄清楚如何去做.
In Objective-C, I would be able to enumerate a view's constraints and adjust the constraints accordingly, but in Swift I'm having difficulty figuring out to do the equivalent.
这是我在 swift 中应用代码的尝试:
here is my attempt at applying the code in swift:
for (index, value) in enumerate(view.constraints()) {
var constraint = value as NSLayoutConstraint
if value.firstItem? = view {
constraint.constant = -200;
}
}
我收到一个编译器错误,指出类型 '[AnyObject!'不符合此代码第一行的协议序列".
I get a compiler error stating "Type '[AnyObject!' does not conform to protocol 'Sequence' on the first line of this code.
任何帮助将不胜感激!
推荐答案
As constraints()
返回 [AnyObject]!
这是可选的所以你需要解开 view.constraints()!
在使用之前.所以解开它使用下面的代码
As constraints()
returns [AnyObject]!
which is optional so you need to unwrap view.constraints()!
before use.So unwrap it Use below code
for (index, value) in enumerate(view.constraints()!) {
var constraint = value as NSLayoutConstraint
if value.firstItem? = view {
constraint.constant = -200;
}
}
你也不能分配 firstItem
因为它是只读属性.我想你想比较它.所以使用 if value.firstItem!作为 UIView == self.view
. 所以使用 `
Also you cannot assign firstItem
as it is readonly property.I think you want to compare it.So use if value.firstItem! as UIView == self.view
.So use `
for (index, value) in enumerate(view.constraints()!) {
var constraint = value as NSLayoutConstraint
if value.firstItem! as UIView == self.view {
constraint.constant = -200;
}
}
这篇关于在 Swift 中枚举视图的 NSLayoutConstraints?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!