Enumerating a view's NSLayoutConstraints in Swift?

让人想犯罪 __ 提交于 2019-12-11 03:06:38

问题


   [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if ((constraint.firstItem == view) && (constraint.firstAttribute == NSLayoutAttributeTop)) {
            constraint.constant = -200;
        }
    }];

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.

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

    }

I get a compiler error stating "Type '[AnyObject!' does not conform to protocol 'Sequence' on the first line of this code.

Any help would be appreciated!


回答1:


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

    }

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

    }


来源:https://stackoverflow.com/questions/25045796/enumerating-a-views-nslayoutconstraints-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!