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
相关产品推荐
相关产品推荐

