如何为可切换的MapKit MapStyle添加pointsOfInterest过滤?
解决MapStyle添加Points of Interest过滤的编译错误
错误原因
你当前的selectedMapStyle是一个返回MapStyle实例的计算属性,比如.standard是已经创建好的样式对象,而不是构造器方法。你尝试用selectedMapStyle(pointsOfInterest: .excludingAll)的方式调用,本质是在对一个实例执行函数调用,这不符合Swift的语法规则,所以编译器报错。
解决方案1:直接在计算属性中配置POI过滤
修改selectedMapStyle,让它直接返回带有POI过滤配置的MapStyle实例,使用时直接传入该属性即可:
import SwiftUI import MapKit struct ContentView: View { private var selectedMapStyle: MapStyle { switch mapType { case 0: .standard(pointsOfInterest: .excludingAll) case 1: .hybrid(pointsOfInterest: .excludingAll) case 2: .imagery(pointsOfInterest: .excludingAll) default: .standard(pointsOfInterest: .excludingAll) } } @State private var mapType: Int = 0 var body: some View { Map() .mapStyle(selectedMapStyle) // 直接使用配置好的样式 .overlay(alignment: .bottom) { Button(action: { mapType = mapType == 0 ? 1 : 0 }) { VStack { Image(systemName: "map") .font(.system(size: 30)) Text("Map Style") .font(.subheadline) } } .padding() .background(.white) .cornerRadius(10) } } } #Preview { ContentView() }
解决方案2:将计算属性改为可传参的方法
如果需要灵活控制不同样式的POI过滤规则(比如部分样式保留POI,部分排除),可以把selectedMapStyle改成接受POI参数的方法:
import SwiftUI import MapKit struct ContentView: View { private func selectedMapStyle(pointsOfInterest: MapStyle.FeatureVisibility) -> MapStyle { switch mapType { case 0: .standard(pointsOfInterest: pointsOfInterest) case 1: .hybrid(pointsOfInterest: pointsOfInterest) // 示例:给imagery样式单独设置POI规则 case 2: .imagery(pointsOfInterest: .includingAll) default: .standard(pointsOfInterest: pointsOfInterest) } } @State private var mapType: Int = 0 var body: some View { Map() // 调用方法并传入POI过滤参数 .mapStyle(selectedMapStyle(pointsOfInterest: .excludingAll)) .overlay(alignment: .bottom) { Button(action: { mapType = mapType == 0 ? 1 : 0 }) { VStack { Image(systemName: "map") .font(.system(size: 30)) Text("Map Style") .font(.subheadline) } } .padding() .background(.white) .cornerRadius(10) } } } #Preview { ContentView() }
两种方案都能解决编译错误:如果所有样式都用相同的POI规则,方案1更简洁;如果需要针对不同样式定制POI规则,方案2更灵活。
内容的提问来源于stack exchange,提问作者steve_sch
相关产品推荐
相关产品推荐

