You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI中ForEach无法遵循VStack leading对齐的问题

SwiftUI中ForEach导致VStack左对齐失效问题

我编写了一段SwiftUI代码,外层是设置了.leading对齐的VStack,但内部通过ForEach渲染的文本全部居中显示,完全不遵循左对齐设置:

VStack(alignment: .leading, spacing: 0) {
    HStack(alignment: .center, spacing: 3) {
        Text("Hours")
            .font(.body.weight(.bold))
    }
    ScrollViewIfNeeded(.vertical, showsIndicators: false) {
        Group {
            if item.hours != [] || !item.hours.isEmpty {
                ForEach(item.hours, id: \.self) { hour in
                    Text(hour)
                }
            } else {
                Text("No hours provided.")
            }
        }
        .font(.footnote)
        .foregroundColor(.secondary)
    }
}
.frame(width: containerWidth * 0.40)

但如果移除ForEach,直接放置多个Text组件,VStack的左对齐就能正常生效:

VStack(alignment: .leading, spacing: 0) {
    HStack(alignment: .center, spacing: 3) {
        Text("Hours")
            .font(.body.weight(.bold))
    }
    ScrollViewIfNeeded(.vertical, showsIndicators: false) {
        Group {
            Text("Hello1")
            Text("Hello2")
            Text("Hello3")
        }
        .font(.footnote)
        .foregroundColor(.secondary)
    }
}
.frame(width: containerWidth * 0.40)

请问ForEach在对齐逻辑上和直接放置Text组件存在什么差异?


更新内容

item的定义为let item: Place,Place结构体代码如下:

struct Place: Codable, Identifiable {
    var hours = [String]()
    
    // MARK: - SET DEFAULT PROPERTIES
    static var `default` : Place {
        Place(
            hours: ("Hours")
        )
    }
    
    init(
        hours: (String)
    ) {
        self.hours = [hours]
    }
    
    init(with p: MGLocation) {
        self.hours = p.hours ?? []
    }
}

内容的提问来源于stack exchange,提问作者theMap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:25:27