gpt4 book ai didi

ios - 使用 GeometryReader 时 SwiftUI 覆盖层的垂直对齐错误

转载 作者:行者123 更新时间:2023-12-01 18:34:56 25 4
gpt4 key购买 nike

我有一个叠加 View ,我希望它看起来紧贴其父 View 的顶部边缘(垂直对齐到顶部而不是中心,请参见快照 B)并且能够在点击时半隐藏它(将其向上移动以便它不会遮挡其父 View ,但仍有一部分可见,比如 64 像素,这样它仍然可以轻按回到原始位置,请参见快照 C)。问题是,当我使用 GeometryReader 获取我试图移动的覆盖 View 的高度时,覆盖最初出现在 View 的中心(参见快照 A)。如果我不使用几何阅读器,我不知道要偏移多少覆盖 View :

    @State var moveOverlay = false

var body : some View {

VStack {
ForEach(0...18, id: \.self) { _ in
Text("This is the background... This is the background... This is the background... This is the background... ")
}
}
.overlay(VStack {
GeometryReader { proxy in
Text("This is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\n")
.lineLimit(9)
.background(Color.gray)
.padding(32)
.frame(maxWidth: nil)
.offset(x: 0, y: self.moveOverlay ? -proxy.size.height + 128 + 64 : 0)
.onTapGesture {
self.moveOverlay = !self.moveOverlay
}
}
Spacer()
})
}

不确定为什么几何阅读器对布局有这种影响。

(A) 这是几何阅读器代码的显示方式:

enter image description here

(B) 如果我删除几何阅读器代码,我会得到预期的效果:

enter image description here

(C) 这就是我希望叠加层移动到顶部时的方式:

enter image description here

编辑:上面显示的代码生成布局 (A)。如果我省略几何阅读器代码,我想要布局 (B)。

最佳答案

好吧......仍然不确定,但这里有一些方法

使用 Xcode 11.4/iOS 13.4 测试

demo

.overlay(
ZStack(alignment: .top) {
Color.clear
Text("This is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\nThis is the overlay text snippet sentence that is multiline...\n")
.lineLimit(9)
.background(Color.gray)
.alignmentGuide(.top) { self.hideOverlay ? $0.height * 3/2 : $0[.top] - 64 }
.onTapGesture {
withAnimation(Animation.spring()) {
self.hideOverlay.toggle()
}
}
})

关于ios - 使用 GeometryReader 时 SwiftUI 覆盖层的垂直对齐错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61445321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com