6

我尝试重新分配一个referecend NSLayoutConstraint。

class ViewController: UIViewController {
    @IBOutlet weak var myConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        exchangeConstraint(&myConstraint)
    }
}

extension UIViewController {
    func exchangeConstraint(_ constraint: inout NSLayoutConstraint) {
        let spacing = constraint.constant
        view.removeConstraint(constraint)
        constraint = view.topAnchor.constraint(equalTo: anotherView.topAnchor, constant: spacing)
        view.addConstraint(constraint)
    }
}

但在这里它给了我错误:

exchangeConstraint(&myConstraint)
-------------------^
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument

我不明白为什么它说不可变值,而约束被声明为变量,而不是常量。

4

1 回答 1

1

我通过简单地将constraint参数声明为显式 unwraped来解决它NSLayoutConstraint

func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
    ...
}

更新

这是我使用它的一个项目:https ://github.com/truffls/compatible-layout-anchors-ios

于 2017-12-07T12:52:58.720 回答