SwiftUI布局问题:如何让HStack内中间VStack精准居中?
SwiftUI布局问题:让中间VStack完美居中于HStack
我有一个包含三个VStack的HStack,想要让中间的VStack完全居中于视图。以下是我的代码和截图,请求解决方法:
HStack(alignment: .center) { VStack(spacing: 10) { WebImage(url: URL(string: "https://images.fotmob.com/image_resources/logo/teamlogo/\(matchDetails.general.homeTeam.id).png")) .resizable() .scaledToFit() .frame(width: 50, height: 50) Text(matchDetails.general.homeTeam.name) .font(.system(size: 15)) .lineLimit(1) }.frame(alignment: .trailing) VStack(spacing: 10) { if let scoreStr = matchDetails.header.status.scoreStr { Text(scoreStr) .font(.system(size: 35)) .fontWeight(.medium) } else if let matchTimeUTC = matchDetails.general.matchTimeUTC { Text(formatTime(from: matchTimeUTC)) .font(.system(size: 35)) .fontWeight(.medium) } if let reasonStr = matchDetails.header.status.reason?.long { Text(reasonStr) .font(.system(size: 15)) } else if let liveTimeStr = matchDetails.header.status.liveTime?.long { Text(liveTimeStr) .font(.system(size: 15)) } } VStack(spacing: 10) { WebImage(url: URL(string: "https://images.fotmob.com/image_resources/logo/teamlogo/\(matchDetails.general.awayTeam.id).png")) .resizable() .scaledToFit() .frame(width: 50, height: 50) Text(matchDetails.general.awayTeam.name) .font(.system(size: 15)) .lineLimit(1) }.frame(alignment: .leading) }.padding(.horizontal) .foregroundStyle(Color.black)

解决方法
问题根源是左右两个VStack的内容宽度不一致(比如球队名称长度不同),导致HStack给它们分配的空间不等,中间VStack无法居中。只需让左右VStack占据相等的最大可用宽度,就能固定中间内容的中心位置:
修改左右两个VStack的frame设置:
- 左侧VStack:添加
maxWidth: .infinity,保持右对齐 - 右侧VStack:添加
maxWidth: .infinity,保持左对齐
修改后的关键代码片段:
// 左侧VStack VStack(spacing: 10) { // ... 原有内容 }.frame(maxWidth: .infinity, alignment: .trailing) // 右侧VStack VStack(spacing: 10) { // ... 原有内容 }.frame(maxWidth: .infinity, alignment: .leading)
这样HStack会将左右两侧的剩余空间平均分配,无论左右内容宽度如何,中间的VStack都会固定在视图的正中心。
内容的提问来源于stack exchange,提问作者Michele de Vita
相关产品推荐
相关产品推荐

