如何完全在ScrollView或VStack中与其他组件一起在Swiftui中显示选取器?

时间:2019-07-18 09:49:21

标签: swiftui watch-os

一旦将Picker放入ScrollView或VStack中,并且其中有更多代码(如ForEach循环),则仅显示Picker标签。

enter image description here 我不知道为什么,因为在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")
                }
            }

        }
    }

}

1 个答案:

答案 0 :(得分:0)

问题出在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