作为标题,我有一个viewParent,它有viewA,
但是在方法awakeAfter中,viewA将被viewB替换。
我想转换所有的约束
从viewParentviewA,
到viewParentviewB。
非常感谢。
这是我的代码:

private func convertConstraints(from: UIView, to: UIView){
        from.constraints.forEach { (constraint: NSLayoutConstraint) in
            let isFirst = (constraint.firstItem as? UIView) == from
            let isSecond = (constraint.secondItem as? UIView) == from

            let first: Any = (isFirst) ? to : constraint.firstItem as Any
            let second: Any? = (isSecond) ? to : constraint.secondItem as? Any

            let new = NSLayoutConstraint(item: first,
                               attribute: constraint.firstAttribute,
                               relatedBy: constraint.relation,
                               toItem: second,
                               attribute: constraint.secondAttribute,
                               multiplier: constraint.multiplier,
                               constant: constraint.constant)
            new.priority = constraint.priority
            new.identifier = constraint.identifier
            new.shouldBeArchived = constraint.shouldBeArchived
            new.isActive = constraint.isActive
        }
    }

控制台日志如下:
2019-03-27 15:36:33.740004+0800 Cale[86571:50392102] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'NSLayoutConstraint for <Cale.AirportButton: 0x7f9eb454d990; baseClass = UIButton; frame = (0 129; 120 120); autoresize = RM+BM; layer = <CALayer: 0x600003936460>>: Unknown layout attribute'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010bf501bb __exceptionPreprocess + 331
    1   libobjc.A.dylib                     0x000000010b4ee735 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010bf50015 +[NSException raise:format:] + 197
    3   Foundation                          0x000000010a16cf61 ResolveConstraintArguments + 372
    4   Foundation                          0x000000010a16d2cb +[NSLayoutConstraint constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:] + 80
.
.
.

最佳答案

我修好了,。。。谢谢。
我修改了代码:

let second: Any? = (isSecond) ? to : constraint.secondItem as? Any

致:
let second: Any? = (isSecond) ? to : constraint.secondItem

10-06 12:23