gpt4 book ai didi

ios - 如何让 VStack 填满 SwiftUI 中的屏幕宽度

转载 作者:行者123 更新时间:2023-11-28 23:21:33 27 4
gpt4 key购买 nike

我正在尝试制作可视化 VStack 属性的 VStack 示例应用

但是我的 VStack 无法填满屏幕的宽度

我在互联网上尝试了很多解决方案(frame modifier、HStack with Spacer、GeometryReader)但它们都不起作用

这是我的代码

父 View

struct LayoutView: View {

@State private var spacing: CGFloat = 0.0
@State private var alignmentIndex = 0
@State private var elementsAmount = 0

private let layout: StackLayout

private let alignments: [String] = [".leading", ".center", ".trailing"]
private let minValue: CGFloat = 0.0
private let maxValue: CGFloat = 100.0

init(_ layout: StackLayout) {
self.layout = layout
}

var body: some View {
NavigationView {
Form {
Section(header: Text("Controls")) {
VStack(alignment: .leading) {
Text("Spacing: \(Int(spacing))").font(.caption)
HStack {
Text("\(Int(minValue))")
Slider(value: $spacing, in: minValue...maxValue, step: 1)
Text("\(Int(maxValue))")
}
}

Picker("alignments", selection: self.$alignmentIndex) {
ForEach(0..<alignments.count) {
Text(self.alignments[$0])
}
}
.pickerStyle(SegmentedPickerStyle())

Stepper("Element's amount: \(elementsAmount)", value: self.$elementsAmount, in: 0...10)
}

Section(header: Text("Canvas")) {
VStackView(spacing: $spacing, alignmentIndex: $alignmentIndex, elementsCount: $elementsAmount)
}
}
.navigationBarTitle(Text(layout.rawValue), displayMode: .inline)
}
}
}

subview

struct VStackView: View {
@Binding var spacing: CGFloat
@Binding var alignmentIndex: Int
@Binding var elementsCount: Int

private let alignments: [HorizontalAlignment] = [.leading, .center, .trailing]

var body: some View {
VStack(alignment: self.alignments[alignmentIndex], spacing: CGFloat(spacing)) {
ForEach(0..<elementsCount, id: \.self) {
Text("\($0)th View")
}
}
}
}

这是结果

enter image description here

最佳答案

我猜你可以像这样更新代码

struct VStackView: View {
@Binding var spacing: CGFloat
@Binding var alignmentIndex: Int
@Binding var elementsCount: Int

private let alignments: [HorizontalAlignment] = [.leading, .center, .trailing]

var body: some View {
VStack(alignment: self.alignments[alignmentIndex], spacing: CGFloat(spacing)) {
ForEach(0..<elementsCount, id: \.self) {
Text("\($0)th View").frame(maxWidth: .infinity, alignment: Alignment(horizontal: self.alignments[self.alignmentIndex], vertical: .center))
}
}
}
}

关于ios - 如何让 VStack 填满 SwiftUI 中的屏幕宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59612330/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com