Consider having dynamic (programmatically calculated) size and position for a view.
While I can easily set width and height to a constant, like:
myView.widthAnchor.constraint(equalToConstant: mySize.width)
Where
widthAnchor
is ofNSLayoutDimension
type.
But I get compile error for each of below:
myView.leadingAnchor.constraint(equalToConstant: 0.0)
myView.leftAnchor.constraint(equalToConstant: 0.0)
Where
leadingAnchor
andleftAnchor
are both ofNSLayoutXAxisAnchor
type.
With error message:
No exact matches in call to instance method 'constraint'
Is there any way to have constant X/Y position using constraint(s)?
Notes:
#1 myView
is the root-view, without any-other-view, hence something like below is not possible:
myView.leadingAnchor.constraint(equalTo: myOtherView.leadingAnchor, constant: 0.0)
But would not make much sense anyway, as now I would get same error, but while trying to give
myOtherView
a constant position.
#2 Above code is Swift 5
, but I tag Obj-C
and Obj-C++
too, as I know those languages, and would understand those answers as well.
Example 2
While a dynamic-position is a general requirement, but to answer comments about why myView
is a root-view, see:
myView.translatesAutoresizingMaskIntoConstraints = false;
if #available(iOS 11.0, *) {
myView.leadingAnchor.constraint(equalTo: myView.safeAreaLayoutGuide.leadingAnchor)
.isActive = true;
// ...
} else {
// Below gives error.
myView.leadingAnchor.constraint(equalToConstant: 0.0)
.isActive = true;
// ...
}
Basically, older iOS versions don’t have safe-area anchor, hence there I need to use a constant.
2
Answers
Here is how I worked-around the limitation:
I think this method
constraint(equalToConstant:)
is deprecated or no more available now.You can use the like: