更新NSLayoutConstraint上的“常量”失败,并且“无法在'约束'中分配给'常量'”

时间:2015-01-17 00:12:20

标签: ios nslayoutconstraint

我的UIView子类中有以下快速代码:

    for constraint in self.constraints() {
        if (constraint.firstItem as UIView == volumeOverlay && constraint.firstAttribute == NSLayoutAttribute.Top) ||
           (constraint.secondItem as UIView == volumeOverlay && constraint.secondAttribute == NSLayoutAttribute.Top) {
            NSLog ("Found constraint. Top is: \(constraint.constant)")
            constraint.constant = 100
        }
    }

我收到编译时错误:

  

... TrackView.swift:25:37:无法在'约束'中分配'常量'

NSLayoutConstraint的文档说

  

与其他属性不同,可以在创建约束后修改常量。在现有约束上设置常量比删除约束并添加一个与旧约束一样的新约会比使用新常量要好得多。

那么我做错了什么我无法更新“常量”变量?

BTW,这是适用于iOS8的XCode 6.1.1

1 个答案:

答案 0 :(得分:0)

好的,我明白了。我没有意识到self.constraints()返回[AnyObject],所以我不得不将“约束”转换为NSLayoutConstraint。

可能有一种更优雅的方式,但这就是我现在所拥有的:

    var y: CGFloat = // do some calculation....
    for constraintObj in self.constraints() {
        if constraintObj.isKindOfClass(NSLayoutConstraint) {
            var constraint = constraintObj as NSLayoutConstraint
            if (constraint.firstItem as UIView == volumeOverlay && constraint.firstAttribute == NSLayoutAttribute.Top) ||
               (constraint.secondItem as UIView == volumeOverlay && constraint.secondAttribute == NSLayoutAttribute.Top) {
                constraint.constant = y
                break
            }
        }
    }

耶。有用。