添加“a”的正确方式是什么;“显示用户位置”;SwiftUI中的MKMapView按钮?

添加“a”的正确方式是什么;“显示用户位置”;SwiftUI中的MKMapView按钮?,mkmapview,swiftui,Mkmapview,Swiftui,我正在尝试创建一个带有MKMapView和一个按钮的SwiftUI视图来导航到用户位置。下面是我的全部代码。我创建了一个名为MapView的视图,它符合UIViewRepresentable以保存我的MKMapView。我有一个位置按钮,点击该按钮时,将shouldNavigateToUserLocation设置为true。这将导致重新加载UI,如果shouldNavigateToUserLocation为true,则myMapView将导航到用户位置。然后,它将shouldNavigateTo

我正在尝试创建一个带有MKMapView和一个按钮的SwiftUI视图来导航到用户位置。下面是我的全部代码。我创建了一个名为
MapView
的视图,它符合
UIViewRepresentable
以保存我的MKMapView。我有一个位置按钮,点击该按钮时,将
shouldNavigateToUserLocation
设置为true。这将导致重新加载UI,如果
shouldNavigateToUserLocation
为true,则my
MapView
将导航到用户位置。然后,它将
shouldNavigateToUserLocation
设置为false,以便在状态发生变化时,MapView不会一直移动到用户位置

这种方法在实际设备上运行时似乎有效,但我得到警告“在视图更新期间修改状态,这将导致未定义的行为。”在第87行,即
shouldNavigateToUserLocation=false
。这是可以理解的,但我的问题是,我如何避免这种情况?我似乎找不到一种方法来重新构造我的代码,这样我就不会违反在视图更新期间不修改状态的规则,同时仍然在用户按下按钮时让地图导航到用户位置

我尝试了几种不同的方法,但我主要遇到的问题是,我的MapView和我的控制器类实际上都没有直接访问MKMapView的权限。我理解为什么在SwiftUI中会出现这种情况,但它确实限制了我的能力

以下是我的全部代码:

导入快捷界面
导入地图套件
结构ContentView:View{
@状态变量currentlyDisplayingLocationAuthorizationRequest=false
@状态变量shouldNavigateToUserLocation=false
让locationManager=CLLocationManager()
var body:一些观点{
ZStack{
地图视图(currentlyDisplayingLocationAuthorizationRequest:$currentlyDisplayingLocationAuthorizationRequest,
shouldNavigateToUserLocation:$shouldNavigateToUserLocation)
HStack{
垫片()
VStack{
垫片()
按钮(操作:{
self.checkforLocationAuthorization和NavigateToUserLocation()
}) {
图像(系统名称:“位置”)
.imageScale(.large)
.可访问性(标签:文本(“定位我”))
.padding()
}
.背景(颜色.灰色)
.转弯半径(10)
.padding()
}
}
}
奥纳佩尔先生{
self.shouldNavigateToUserLocation=true
}
}
func CheckForLocationAuthorization和NavigateToUserLocation()检查{
currentlyDisplayingLocationAuthorizationRequest=false
如果CLLocationManager.authorizationStatus()=未确定{
打印(“未确定位置授权”)
currentlyDisplayingLocationAuthorizationRequest=true
locationManager.RequestWhenUseAuthorization()
返回
}
shouldNavigateToUserLocation=true
}
}
结构映射视图:UIViewRepresentable{
@绑定变量currentlyDisplayingLocationAuthorizationRequest:Bool
@绑定变量shouldNavigateToUserLocation:Bool
让locationManager=CLLocationManager()
func makeUIView(上下文:context)->MKMapView{
让map=MKMapView()
map.delegate=context.coordinator
map.showsUserLocation=true
返回图
}
func updateUIView(uiView:MKMapView,context:context){
如果!currentlyDisplayingLocationAuthorizationRequest&&shouldNavigateToUserLocation{
moveToUserLocation(地图:uiView)
}
}
func makeCoordinator()->Coordinator{
协调员(自我)
}
//标记:位置-
专用func moveToUserLocation(映射:MKMapView){
guard let location=locationManager.location else{return}
设region=MKCoordinateRegion(中心:location.coordinate,
span:MKCoordinateSpan(纬度:0.02,
纵向数据(单位:0.02))
map.setRegion(区域,动画:true)
shouldNavigateToUserLocation=false
}
//马克:协调员-
最终类协调器:NSObject,MKMapViewDelegate{
变量控件:MapView
init(u控制:MapView){
自我控制
}
}
}

这不完全是您要搜索的内容,但您应该看看另一个相关问题()。我认为它可以帮助你,或者其他人,如果他们面临同样的问题。

我在另一篇帖子中回答了这个问题:,或者你可以在我的github中参考我的演示项目: