如何在 Swiftui 中将 Picker 完全显示在 ScrollView 或 VStack 与其他组件中?
How to display a Picker in Swiftui completely in a ScrollView or VStack with other components?
只要我将 Picker 放入 ScrollView 或 VStack 中,并且其中有更多代码(如 ForEach 循环),就只会显示 Picker-label。
我想知道为什么,因为在 Scrollview 之外或单独显示它是正确的。
代码如下:
@State private var exercises = ["Unterarmstütz", "Dehnen", "Kopfstand", "Handstand"]
@State private var selectedExercise = "Plank"
@State private var selectedTimeIndex = 60
var body: some View {
VStack {
ScrollView {
Picker(selection: $selectedTimeIndex, label: Text("select Time")) {
Text("Option 1")
Text("Option 2")
Text("Option 3")
}
ForEach(exercises.identified(by: \.self)) { exercise in
Button(action: {
self.selectedExercise = String("exercise")
}) {
Text("exercise")
}
}
}
}
}
问题是 ScrollView
,如果您在 ScrollView
中放置任何内容,则必须设置它的框架。
在这里你可以做到,
@State private var exercises = ["Unterarmstütz", "Dehnen", "Kopfstand", "Handstand"]
@State private var selectedExercise = "Plank"
@State private var selectedTimeIndex = 60
var body: some View {
//use GeometryReader for height & weight//
GeometryReader { geometry in
ScrollView() {
VStack {
Picker(selection: self.$selectedTimeIndex, label: Text("select Time")) {
Text("Option 1")
Text("Option 2")
Text("Option 3")
}.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
ForEach(self.exercises, id: \.self) { exercise in
Button(action: {
self.selectedExercise = String("exercise")
}) {
Text("exercise")
}
}
}
}
}
}
注意:我正在使用 Xcode 11 Beta 4
只要我将 Picker 放入 ScrollView 或 VStack 中,并且其中有更多代码(如 ForEach 循环),就只会显示 Picker-label。
代码如下:
@State private var exercises = ["Unterarmstütz", "Dehnen", "Kopfstand", "Handstand"]
@State private var selectedExercise = "Plank"
@State private var selectedTimeIndex = 60
var body: some View {
VStack {
ScrollView {
Picker(selection: $selectedTimeIndex, label: Text("select Time")) {
Text("Option 1")
Text("Option 2")
Text("Option 3")
}
ForEach(exercises.identified(by: \.self)) { exercise in
Button(action: {
self.selectedExercise = String("exercise")
}) {
Text("exercise")
}
}
}
}
}
问题是 ScrollView
,如果您在 ScrollView
中放置任何内容,则必须设置它的框架。
在这里你可以做到,
@State private var exercises = ["Unterarmstütz", "Dehnen", "Kopfstand", "Handstand"]
@State private var selectedExercise = "Plank"
@State private var selectedTimeIndex = 60
var body: some View {
//use GeometryReader for height & weight//
GeometryReader { geometry in
ScrollView() {
VStack {
Picker(selection: self.$selectedTimeIndex, label: Text("select Time")) {
Text("Option 1")
Text("Option 2")
Text("Option 3")
}.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
ForEach(self.exercises, id: \.self) { exercise in
Button(action: {
self.selectedExercise = String("exercise")
}) {
Text("exercise")
}
}
}
}
}
}
注意:我正在使用 Xcode 11 Beta 4