[英]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)。
struct DemoImplicitAlignment: View {
var body: some View {
ZStack(alignment: .topLeading) {
Text("First").border(Color.green)
Text("Second").border(Color.red)
}
}
}
明確的情況:我們不喜歡重疊的文本,並希望第二個文本低於並相對於第一個文本按指定移動。
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.