Reputation: 1902
What is the purpose of the explicit alignment guide in SwiftUI? I don't understand how this is different from a normal 'implicit' guide. The document says:
Returns the explicit value of the given alignment guide in this view, or
nil
if no such value exists.
From this post, I can see that explicit guide is the guide I defined using the
public func alignmentGuide(_ g: HorizontalAlignment, computeValue: @escaping (ViewDimensions) -> CGFloat) -> some View
method. However, I can't understand how this value can be used to align views from an outer scope.
Is there an example to see how this "explicit" alignment guide works in practice?
Upvotes: 5
Views: 1058
Reputation: 257493
Alignment guides are present always. Container defines which alignment guides of internal views should be used by layout engine to align views within container.
If you don't do anything with alignment guile's then implicit/default are used by layout engine.
As soon as you use .alignmentGuide()
modifier for view - you introduce explicit alignment guide
Here is an example of ZStack
with top-leading alignment having two Text
views.
Default/implicit case: both text aligned to top and left (top = 0, leading = 0), so Second just overlaps first (as this is ZStack).
struct DemoImplicitAlignment: View {
var body: some View {
ZStack(alignment: .topLeading) {
Text("First").border(Color.green)
Text("Second").border(Color.red)
}
}
}
Explicit case: we don't like overlapped texts and want second one be below & shifted as specified relative to first one.
struct DemoExplicitAlignment: View {
var body: some View {
ZStack(alignment: .topLeading) {
Text("First").border(Color.green)
Text("Second").border(Color.red)
// now my top alignment guide shifted from implicit/default one
// on specified constant, so I have space above self
.alignmentGuide(.top) { $0[.top] - 40 }
// now my leading alignment guild shifted based on above
// explicit own top alignment guide, so I have variation
// free space ahead of self
.alignmentGuide(.leading) { $0[explicit: .top]! / 2 }
}
}
}
And container, ie. ZStack, tight around most consumed intrinsic space, by default.
In the referenced topic you can find what can be done with just alignment guides SwiftUI HStack with wrap and dynamic height
And many others real examples just by search
Upvotes: 5