SwiftUI中如何让VStack对齐到Toolbar下方的视图顶部
SwiftUI:VStack元素无法从Toolbar下方顶部布局的问题及解决
问题描述
需要实现VStack中的元素从Toolbar下方的屏幕顶部开始布局,但多次尝试均未成功,相关代码如下:
// // ContentView.swift // Led Controller // // // import SwiftUI let R:CGFloat = 30 let screenRect = UIScreen.main.bounds let screenWidth = screenRect.size.width let screenHeight = screenRect.size.height struct ContentView: View { var body: some View { NavigationStack { ZStack { Image("background") .resizable() .aspectRatio(contentMode: .fill) MainUI() } .toolbarBackground(Color.black, for: .navigationBar) .toolbarBackground(.visible, for: .navigationBar) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .principal) { Text("LED Controller") .font(.largeTitle) .accessibilityAddTraits(.isHeader) .foregroundStyle(LinearGradient( colors: [.blue, .green, .brown, .pink], startPoint: .leading, endPoint: .trailing )) } } } } } struct MainUI: View { var body: some View { VStack(alignment: .leading) { Text("Placeholder") .background(RoundedRectangle(cornerRadius: R) .fill(Color.black) .frame(width: screenWidth/2, height: 40)) } } } #Preview { ContentView() }
尝试过的无效方案
- 在多个位置添加
Spacer(),结果将Placeholder移出屏幕 - 移除Toolbar后,Placeholder仍仅底部少量像素可见
- 使用
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)设置对齐无效果
最终解决
更换背景图后问题自行解决。
内容的提问来源于stack exchange,提问作者KP101Coder
相关产品推荐
相关产品推荐

