Missing Anchors

Anton Bukov Blocked Unblock Follow Following Nov 9, 2016

Hey iOS/macOS/watchOS/tvOS developers! I wanna tell you about one simple but interesting code formatting trick we use in Machine Learning Works to describe autolayout constraints.

I was really impressed when I met Apple NSLayoutAnchor API for the first time, which was introduced as a part of iOS 9 SDK. Just want to remind you all of its features:

centerXAnchor/centerYAnchor

topAnchor/bottomAnchor

leftAnchor/rightAnchor

leadingAnchor/trailingAnchor

widthAnchor/heightAnchor

firstBaselineAnchor/lastBaselineAnchor

After awhile I decided that Apple has missed a few possible features:

sizeAnchor

edgesAnchor

Size anchor just provides a shorter way to specify width and height with a single CGSize value. Edges anchor allows to specify UIEdgeInset value relatively to superview bounds. Edges anchor also supports some additional modifiers:

withoutTopAnchor/withoutBottomAnchor

withoutLeadingAnchor/withoutTrailingAnchor

withTopAnchor/withBottomAnchor

withLeadingAnchor/withTrailingAnchor

Some Objective-C examples:

The eagle-eyed of you might have noticed — I’ve just forgot to activate one of the constraints. Thats why I’ve developed a new way to activate them:

Even such syntax is legal with MissingAnchors library:

Finally, I was so impressed with Apple NSLayoutAnchors API that I had backported it to iOS 7 🎉

Also I am thinking about 2-dimensional anchors like centerAnchor/topLeftAnchor/centerRightAnchor… Do you think it will be useful?

https://github.com/k06a/MissingAnchors/