SwiftUI使用非废弃MapKit接口导致自定义导航栏失效求助
SwiftUI 现代Map接口导致自定义导航栏失效问题
在SwiftUI开发中,使用非废弃的Map()接口时,自定义导航栏会失效,转而显示系统默认导航栏,目前尚未找到该问题的解决方案,相关代码及场景如下:
自定义导航栏实现代码
import SwiftUI struct CustomNavigationBarView: ViewModifier { @Environment(\.presentationMode) var presentationMode var showBackButton: Bool init(showBackButton: Bool = false) { self.showBackButton = showBackButton let navBarAppearance = UINavigationBarAppearance() navBarAppearance.titleTextAttributes = [.foregroundColor: UIColor(Color.white)] UINavigationBar.appearance().standardAppearance = navBarAppearance UINavigationBar.appearance().compactAppearance = navBarAppearance UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance navBarAppearance.configureWithTransparentBackground() navBarAppearance.backgroundImage = makeLinearGradient( size: .init(width: 1, height: 1), colors: [.nav1, .nav2] ) navBarAppearance.shadowImage = UIImage() } func body(content: Content) -> some View { content .navigationBarBackButtonHidden(true) .toolbar { if showBackButton { ToolbarItem(placement: .navigationBarLeading) { Button(action: { presentationMode.wrappedValue.dismiss() }) { HStack { Image(systemName: "chevron.left") .foregroundColor(.white) } } } } } } } func makeLinearGradient(size: CGSize, colors: [UIColor]) -> UIImage { let renderer = UIGraphicsImageRenderer(size: size) let colors: [CGColor] = colors.map({ $0.cgColor }) let gradient = CGGradient( colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: [0, 1] ) return renderer.image { context in if let gradient { context.cgContext.drawLinearGradient( gradient, start: CGPoint(x: 0, y: 1), end: CGPoint(x: size.width, y: size.height), options: .init() ) } } }
extension View { func navigationBarModifier(showBackButton: Bool = false) -> some View { self.modifier(CustomNavigationBarView(showBackButton: showBackButton)) .navigationBarTitleDisplayMode(.inline) } }
Map使用场景对比
可保留自定义导航栏的废弃Map接口
以下方式使用Map函数可保留自定义导航栏,但该接口已废弃,需避免使用:
let annotations = [ City(name: "London", coordinate: CLLocationCoordinate2D(latitude: 41.015137, longitude: 28.979530)) ] @State private var region = MKCoordinateRegion( center: CLLocationCoordinate2D(latitude: 41.015137, longitude: 28.979530), span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) ZStack(alignment: .bottom) { Map(coordinateRegion: $region, annotationItems: annotations) { annotation in MapAnnotation(coordinate: annotation.coordinate) { Image("map-loc") .resizable() .frame(width: 25, height: 33) } } }
破坏自定义导航栏的现代Map接口
以下方式及其他现代Map接口均会破坏自定义导航栏,无法达到预期效果:
let cameraPosition: MapCameraPosition = .region(.init(center: .init(latitude: 41.015137, longitude: 28.979530), latitudinalMeters: 1300, longitudinalMeters: 1300)) ZStack(alignment: .bottom) { Map(initialPosition: cameraPosition) { Annotation("map", coordinate: .appleHQ, anchor: .bottom) { Image(systemName: "map-loc") .resizable() } } }
内容的提问来源于stack exchange,提问作者Derya Karakus
相关产品推荐
相关产品推荐

