If I had to name an aspect of SwiftUI development that initially confounded me, it would be alignment guides. As such, I decided to write this article to try to demystify them a little, map out how you can work with them, and indeed make them work for you.
如果我不得不说起最初使我困惑的SwiftUI开发的一个方面,那就是对齐指南。 因此,我决定写这篇文章,试图使它们变得神秘,并阐明如何与他们合作,并确实使它们为您服务。
Alignment guides in SwiftUI are like constraints in UIKit. No, I take that back. They are constraints in SwiftUI — only instead of micromanaging your screen, they macromanage it. You need macro-management for screens these days because they come in all shapes and sizes. However, much like constraints, alignment guides aren’t always that easy to use.
SwiftUI中的对齐指南类似于UIKit中的约束。 不,我拿回去。 它们是SwiftUI中的约束-只是对屏幕进行宏观管理,而不是对其进行微观管理。 如今,您需要对屏幕进行宏管理,因为它们具有各种形状和大小。 但是,就像约束一样,对齐指南并不总是那么容易使用。
The first thing you need to appreciate is the semantics behind the layout mechanism in SwiftUI. The best place to learn about that is Dave Abrahams and John Harper’s talk at 2019 WWDC on the subject. In it, they outline three golden rules for layout:
您需要了解的第一件事是SwiftUI中的布局机制背后的语义。 最好的学习方法是Dave Abrahams和John Harper在2019年WWDC上有关该主题的演讲 。 在其中,他们概述了布局的三个黄金法则:
- Parent proposes a size for the child. 父母为孩子建议一个尺寸。
- Child uses proposal to determine its own size. 儿童使用提案确定自己的尺寸。
- Parent uses that size chosen by the child to position said child. 父母使用孩子选择的尺寸放置孩子。
“What does this have to do with alignment guides?” you may ask. Absolutely everything. To lay out/manage space in SwiftUI, you use containers (ZStack, VStack, and HStack). Containers that are the parents in the semantics above, containers that will organize their siblings using said rules. You can influence these rules with your alignment guides. But wait, there is a snag. Normally, the