SwiftUI View viene spostato a destra quando si utilizza Geometry Reader e ScrollVIew
Sep 24 2020
Sto usando uno ScrollView all'interno di un GeometryReader in SwiftUI, ma tutto all'interno della visualizzazione a scorrimento viene spostato a sinistra, o almeno gli elementi all'interno della visualizzazione a scorrimento pensano che il limite della visualizzazione si estenda ben oltre il limite effettivo della visualizzazione. come si vede sotto. Sto usando la versione pubblica di Xcode 12 dall'app store del mac insieme a macOS Big Sur beta 8.
Ecco il codice per ricrearlo.
struct TextClassifierMMLView: View {
@State var nLayers = 5
var body: some View {
GeometryReader{ geo in
ScrollView{
VStack{
GrayNumberStepperCard(text: "Layers", geo: geo, upperRange: 1000, lowerRange: 1, value: self.$nLayers).padding() } } }.navigationTitle(Text("Text Classifier")) } } struct GrayNumberStepperCard: View { @State var text: String @State var geo: GeometryProxy @State var upperRange: Int @State var lowerRange: Int @Binding var value: Int var body: some View { HStack{ Text(text) .font(.custom("OpenSans-SemiBold", size: 14)) .foregroundColor(.accentColor) Spacer() Stepper(value: $value, in: lowerRange...upperRange) {
Text("\(self.value)")
}.padding()
}.frame(width: geo.size.width, height: 15)
.padding()
.background(
RoundedRectangle(cornerRadius: 4)
.foregroundColor(Color(hex: "F0F5F5"))
)
.padding(.horizontal)
.padding(.vertical, 5)
}
}
Risposte
1 Asperi Sep 24 2020 at 10:25
Non è affatto necessario GeometryReaderin questo layout, confonde solo il layout automatico.
Ecco il codice modificato. Testato con Xcode 12 / iOS 14
struct TextClassifierMMLView: View {
@State var nLayers = 5
var body: some View {
ScrollView{
VStack{
GrayNumberStepperCard(text: "Layers", upperRange: 1000, lowerRange: 1, value: self.$nLayers).padding() } }.navigationTitle(Text("Text Classifier")) } } struct GrayNumberStepperCard: View { @State var text: String @State var upperRange: Int @State var lowerRange: Int @Binding var value: Int var body: some View { HStack{ Text(text) .font(.custom("OpenSans-SemiBold", size: 14)) .foregroundColor(.accentColor) Spacer() Stepper(value: $value, in: lowerRange...upperRange) {
Text("\(self.value)")
}.padding()
}.frame(height: 15)
.padding()
.background(
RoundedRectangle(cornerRadius: 4)
.foregroundColor(Color.red)
)
.padding(.horizontal)
.padding(.vertical, 5)
}
}