我试图在屏幕顶部放置一个可滚动的水平列表,堆叠在地图的顶部。我可以在那里放置一个 Text 视图,但是当我尝试在那里放置一个 ScrollView 时,它会留在中心。我究竟做错了什么?
我的代码
//
// TestUIFile.swift
//
import SwiftUI
import MapKit
struct TestUIFile: View {
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var body: some View {
ZStack(alignment: .top) {
Map(coordinateRegion: $region)
Text("Why am I at the top?")
//but I am in the center?
ScrollView(.horizontal) {
LazyHStack {
ForEach(0...50, id: \.self) { index in
Text(String(index))
}
}
}
}
}
}
struct TestUIFile_Previews: PreviewProvider {
static var previews: some View {
TestUIFile()
}
}
答案 0 :(得分:0)
我想通了。
//
// TestUIFile.swift
//
import SwiftUI
import MapKit
struct TestUIFile: View {
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var body: some View {
ZStack(alignment: .top) {
Map(coordinateRegion: $region)
//but I am in the center?
ScrollView(.horizontal) {
LazyHStack {
ForEach(0...50, id: \.self) { index in
Text(String(index))
}
}.frame(width: .infinity, height: 100, alignment: .top)
}
}
}
}
struct TestUIFile_Previews: PreviewProvider {
static var previews: some View {
TestUIFile()
}
}
答案 1 :(得分:0)
屏幕顶部的可滚动水平列表堆叠在地图顶部
这是垂直布局,因此您应该使用 VStack
,而不是 ZStack
。
struct TestUIFile: View {
@State private var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 51.507222, longitude: -0.1275), span: MKCoordinateSpan(latitudeDelta: 0.5, longitudeDelta: 0.5))
var body: some View {
VStack { /// here!
Text("Why am I at the top?")
ScrollView(.horizontal) {
LazyHStack {
ForEach(0...50, id: \.self) { index in
Text(String(index))
}
}
}
.fixedSize(horizontal: false, vertical: true) /// prevent growing too tall
Map(coordinateRegion: $region)
}
}
}
结果: