我试图使用ZStack和字段的几何形状-位置和大小将ListView直接定位在文本字段下方。这是为了创建自动完成选择列表
设置偏移量似乎只能完成一半。
到目前为止,它看起来如下。
仿真器和设备显示在右侧:
一些有用的信息:
https://swiftui-lab.com/geometryreader-to-the-rescue/
import SwiftUI
struct TestView: View {
@State private var firstname = ""
@State private var lastname = ""
@State private var townCity = ""
@State private var rect: CGRect = CGRect()
var body: some View {
ZStack (alignment: .topLeading){
VStack{
Form {
Section {
TextField("Firstname", text: $firstname)
TextField("Lastname", text: $lastname)
ZStack{
VStack (alignment: .leading, spacing: 0){
TextField("Town/City", text: self.$townCity)
.background(GeometryGetterV2(rect: $rect))
}
.border(Color.black, width: 1)
}
Button("Save") {
}
}
}
}
SelectionsPickerV2()
.offset(x: rect.origin.x, y: rect.origin.y)
//.offset(x: rect.minX, y: rect.minY)
.frame(
width: rect.size.width,
height: rect.size.height * 7)
}
.coordinateSpace(name: "myZstack")
}
}
struct SelectionsPickerV2: View {
var body: some View {
VStack (alignment: .leading) {
List{
Text("Sydney, Australia")
Text("New York, New York")
Text("London, UK")
Text("Paris, France")
}
.background(Color.blue)
}
.border(Color.red, width: 1)
}
}
struct TestView_Previews: PreviewProvider {
static var previews: some View {
TestView()
}
}
struct GeometryGetterV2: View {
@Binding var rect: CGRect
var body: some View {
return GeometryReader { geometry in
self.makeView(geometry: geometry)
}
}
func makeView(geometry: GeometryProxy) -> some View {
DispatchQueue.main.async {
self.rect = geometry.frame(in: .named("myZstack"))
//self.rect = geometry.frame(in: .local)
//self.rect = geometry.frame(in: .global)
}
return Rectangle().fill(Color.clear)
}
}
答案 0 :(得分:0)
正如很多人提到的那样,您的ZStack
是顶级视图,随着导航栏的添加,几何计算错误,等等。可能只是另一个SwiftUI错误。
要解决此问题,只需将您的ZStack
嵌入新的父视图中。
struct TestView: View {
// ...
var body: some View {
VStack { // New parent view
ZStack (alignment: .topLeading){
// ...
}
SelectionsPickerV2()
.offset(x: rect.origin.x, y: rect.origin.y)
.frame(
width: rect.size.width,
height: rect.size.height * 7)
}
.coordinateSpace(name: "myZstack") // Fixed coordinate space
}
}
}
答案 1 :(得分:-1)