繁体   English   中英

了解 SwiftUI 的显式 alignment

[英]Understanding the explicit alignment of SwiftUI

SwiftUI 中明确的 alignment 指南的目的是什么? 我不明白这与普通的“隐式”指南有何不同。 文件说:

返回此视图中给定 alignment 指南的显式值,如果不存在此类值,则返回nil

这篇文章中,我可以看到显式指南是我使用定义的指南

public func alignmentGuide(_ g: HorizontalAlignment, computeValue: @escaping (ViewDimensions) -> CGFloat) -> some View

方法。 但是,我无法理解如何使用此值来对齐外部 scope 的视图。

有没有一个例子来看看这个“明确的”alignment 指南在实践中是如何工作的?

1) Alignment 指南始终存在。 容器定义了布局引擎应使用哪些 alignment 内部视图指南来对齐容器内的视图。

2)如果您不使用 alignment guile 做任何事情,那么布局引擎将使用隐式/默认值。

3)一旦您使用.alignmentGuide()修饰符进行查看 - 您就会引入明确的 alignment 指南

这是ZStack的示例,它具有顶级 alignment 具有两个Text视图。

默认/隐式情况:两个文本都对齐到顶部和左侧(顶部 = 0,前导 = 0),所以 Second 只是首先重叠(因为这是 ZStack)。

演示1

struct DemoImplicitAlignment: View {
    var body: some View {
        ZStack(alignment: .topLeading) {
            Text("First").border(Color.green)
            Text("Second").border(Color.red)
        }
    }
}

明确的情况:我们不喜欢重叠的文本,并希望第二个文本低于并相对于第一个文本按指定移动。

演示2

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 }
        }
    }
}

和容器,即。 ZStack,默认情况下紧紧围绕着最消耗的内在空间。

在引用的主题中,您可以找到仅使用 alignment 指南SwiftUI HStack 可以完成的操作,带环绕和动态高度

和许多其他的真实例子只是通过搜索

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM