ios - 理解 SwiftUI 的显式对齐

标签 ios swift swiftui

explicit alignment guide的目的是什么?在 SwiftUI 中?
我不明白这与正常的“隐式”指南有何不同。
该文件说:

Returns the explicit value of the given alignment guide in this view, or nil if no such value exists.



来自 this post ,我可以看到显式指南是我使用

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

方法。
但是,我无法理解如何使用此值从外部范围对齐 View 。

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

最佳答案

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

2)如果您不对对齐诡计做任何事情,则布局引擎将使用隐式/默认值。

3) 一旦您使用 .alignmentGuide() View 修饰符 - 您引入了明确的对齐指南

以下是 ZStack 的示例顶部领先的对齐方式有两个 Text意见。

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

demo1

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

显式案例:我们不喜欢重叠的文本,并希望第二个文本低于并按照指定的相对于第一个文本进行移位。

demo2
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 紧密围绕消耗最多的内部空间。

在引用主题中,您可以找到仅使用对齐指南即可完成的工作 SwiftUI HStack with wrap and dynamic height

还有许多其他真实的例子just by search

关于ios - 理解 SwiftUI 的显式对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61186217/

相关文章:

iOS8.2 不播放来自 parse.com 应用程序的自定义警报声音

ios - Cocoa Pods Shell 脚本调用错误

ios - Sprite-Kit:节点不会向左移动

swift CGPDF文档解析

swiftui - TabView tabItem 图像移至顶部

ios - 根据indexPath Swift在TableView中设置UiCell文本颜色

ios - 'identity' 在 SwifUI 中是什么意思以及我们如何更改某些东西的 'identity'

ios - Xcode View 层次结构调试器不会在鼠标拖动时旋转 View

objective-c - 在 Objective-C 中转换相同的代码会得到另一个数值结果

ios - 将字符串中单词的每个首字母大写