SwiftUI优化分数展示:解决删除分数时标题偏移问题
修复SwiftUI分数展示布局偏移问题
你的问题根源在于VStack固定了100的高度,且默认是居中对齐。当分数条目被删除后,内容总高度缩小,居中对齐会让标题自然向下偏移,解决思路有两种:
方案一:移除固定高度,让布局自适应内容
这种方式最自然,布局会根据实际显示的分数条目自动调整高度,标题位置不会受条目数量影响:
VStack(alignment: .center, spacing: 8) { // 统一设置元素间距,布局更可控 Text("The score for 10 questions") .foregroundStyle(.white) .bold() Rectangle() .frame(width: 210, height: 2) .foregroundColor(.gray) ForEach(Array(playerItems.enumerated()), id: \.offset) { offset, item in let rankText: String switch offset { case 0: rankText = "Best score : \(item.playerScore)" case 1: rankText = "2nd score : \(item.playerScore)" case 2: rankText = "3rd score : \(item.playerScore)" default: rankText = "" // 处理超出前3名的情况 } if !rankText.isEmpty { Text(rankText) .foregroundColor(.white) .bold() } } .onTapGesture { do { try context.delete(model: PlayerItem.self) } catch { print("Failed to clear all Country and City data.") } } } .padding(.vertical, 10) // 用上下padding控制整体间距,替代原有的局部bottom padding
方案二:保留固定高度,设置顶部对齐
如果你的UI要求必须保持100的高度,给VStack设置顶部对齐,这样内容始终从顶部开始排列,标题位置不会偏移:
VStack(alignment: .center, spacing: 8) { Text("The score for 10 questions") .foregroundStyle(.white) .bold() Rectangle() .frame(width: 210, height: 2) .foregroundColor(.gray) ForEach(Array(playerItems.enumerated()), id: \.offset) { offset, item in let rankText: String switch offset { case 0: rankText = "Best score : \(item.playerScore)" case 1: rankText = "2nd score : \(item.playerScore)" case 2: rankText = "3rd score : \(item.playerScore)" default: rankText = "" } if !rankText.isEmpty { Text(rankText) .foregroundColor(.white) .bold() } } .onTapGesture { do { try context.delete(model: PlayerItem.self) } catch { print("Failed to clear all Country and City data.") } } } .frame(height: 100, alignment: .top) // 固定高度同时指定顶部对齐 .padding(.bottom, 10)
另外补充了两个小优化:用switch替代多个if-else让代码更整洁,增加了超出前3名的空文本处理,避免显示无效内容。
内容的提问来源于stack exchange,提问作者Iku
相关产品推荐
相关产品推荐

