SwiftUI界面上下出现大黑边问题求助
SwiftUI视图扩展至安全区域边界:消除上下黑边问题
在SwiftUI学习示例App中,界面顶部和底部出现不必要的黑边,需要将视图扩展到安全区域的上下边界。环境为Xcode 13.4.1、iOS 15.5,相关代码如下:
相关代码
ContentView代码
import SwiftUI struct ContentView: View { var body: some View { TabView { HotelView() .tabItem { Image(systemName: "house") .resizable() Text("Home") } HomeView(title: "My Trips") .tabItem { Image(systemName: "suitcase") Text("My Trips") } HomeView(title: "Saved") .tabItem { Image(systemName: "heart") Text("Saved") } HomeView(title: "Profile") .tabItem { Image(systemName: "person") Text("Profile") } } .frame(maxWidth: .infinity, maxHeight: .infinity) } }
HotelView代码
import SwiftUI struct HotelView: View { var body: some View { NavigationView { List(hotels) { hotel in ScrollView(.vertical, showsIndicators: true) { NavigationLink(destination: DetailView(hotels: hotel)) { HStack { Image(hotel.image) .resizable() .frame(height: 100) .frame(maxWidth: .infinity) .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous)) .overlay( Text(hotel.city) .fontWeight(.bold) .foregroundColor(.white),alignment: .center) } } } } // navtitle } } }
App入口代码
import SwiftUI @main struct Mohsin_city_plannerApp: App { var body: some Scene { WindowGroup { ContentView() } } }
解决方案
要消除上下黑边并让视图填满安全区域,只需两处修改:
- 让TabView忽略安全区域
在ContentView的TabView上添加edgesIgnoringSafeArea(.all)修饰符,打破安全区域的限制:
TabView { // 原有tab项内容不变 } .frame(maxWidth: .infinity, maxHeight: .infinity) .edgesIgnoringSafeArea(.all) // 添加此行
- 调整NavigationView与List的安全区域适配
在HotelView中,给NavigationView和List分别添加垂直方向的安全区域忽略设置,确保内容填满上下空间:
NavigationView { List(hotels) { hotel in // 原有List内容不变 } .edgesIgnoringSafeArea(.vertical) // 让List扩展至上下边界 } .edgesIgnoringSafeArea(.vertical) // 让NavigationView忽略垂直安全区域
注:iOS 15及以上版本中,NavigationView和List默认会保留安全区域内边距,显式添加edgesIgnoringSafeArea可以覆盖这一默认行为,实现视图全屏扩展。
内容的提问来源于stack exchange,提问作者macspeed
相关产品推荐
相关产品推荐

