I want to use Apples visual format language to constrain a view to the new Safe Area Layout Guide in iOS 11. However, I get an exception:
-[NSLayoutYAxisAnchor nsli_superitem]: unrecognized selector sent to instance 0x1c447ed40
//Make View Dictionary
var views: [String: Any] = ["left": self.leftContainer]
//Check swift version and add appropriate piece to the view dictionary
if #available(iOS 11, *) {
views["topGuide"] = self.view.safeAreaLayoutGuide.topAnchor
}else{
views["topGuide"] = self.topLayoutGuide
}
//Make the constraint using visual format language
let leftVertical = NSLayoutConstraint.constraints(withVisualFormat: "V:[topGuide][left]|", options: [], metrics: nil, views: views)
//Add the new constraint
self.view.addConstraints(vertical)
The reason I like visual format language is because you a can add lot of constraints with less code in some cases.
Any Ideas?
You can't. There is no access to the safe area layout guide through the visual format language. I've filed a bug on this, and I suggest you do the same.
I know it's not VFL, but there is a factory class called
NSLayoutAnchor
that makes creating constraints a bit more clean and concise.For example, I was able to pin the top anchor of a UILabel to the top anchor of the safe area with one compact line:
Note that
safeAreaLayoutGuide
requires iOS 11. For older versions, replaceself.view.safeAreaLayoutGuide.topAnchor
byself.topLayoutGuide.bottomAnchor
.Again, I know it's not VFL, but this seems to be what we have for now.
We've extended the visual formatting language here a bit, so now you can pin against "<|" when you mean safeAreaLayoutGuide. I wish Apple did something like that.
For example, if you have the following pre iOS 11 code:
And now you want to make sure that the button sits above the safe bottom margin on iPhone X, then do this:
That's it. It'll anchor the button to the bottom of its superview on iOS 9 and 10, but anchor it to the bottom of its safeAreaLayoutGuide on iOS 11.
Please note that using "|>" to pin to the top won't exclude the status bar on iOS 9 and 10.