I try to reassign an 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)
}
}
But here it gives me the error:
exchangeConstraint(&myConstraint)
-------------------^
Cannot pass immutable value of type 'NSLayoutConstraint' as inout argument
What i don't understand is why it says immutable value, whereas the constraint is declared as a variable, not a constant.
I solved it by simply declaring the constraint
parameter as an explicitly unwraped NSLayoutConstraint
.
func exchangeConstraint(_ constraint: inout NSLayoutConstraint!) {
...
}
UPDATE
Here is a project where I use it: https://github.com/truffls/compatible-layout-anchors-ios
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With