【发布时间】:2019-10-26 10:56:36
【问题描述】:
我正在尝试加载地图并在用户位置上显示初始位置,并使用 SwiftUI 在地图上显示用户的位置。我不知道如何在 SwiftUI 中做到这一点。
我尝试将“view.showsUserLocation = true”放入 updateUIView 函数中,但它不起作用。
import SwiftUI
import MapKit
struct MapView : UIViewRepresentable {
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
view.showsUserLocation = true
let coordinate = CLLocationCoordinate2D(
latitude: 34.011286, longitude: -116.166868)
let span = MKCoordinateSpan(latitudeDelta: 2.0, longitudeDelta: 2.0)
let region = MKCoordinateRegion(center: view.userLocation.location?.coordinate ?? coordinate, span: span)
view.setRegion(region, animated: true)
}
}
当我尝试打印时,位置为零。
【问题讨论】:
-
你试过在真机上测试这个吗?当涉及到
Core Location时,模拟器可能很繁琐——还要确保当前方案允许位置模拟:Current Scheme -> Edit -> Run -> Options ->Allow Location Simulation -
是的,我已经这样做了,并确保我输入了一个位置。我还在移动设备上进行了测试。我还在 info.plist 中添加了权限