我有一个地图视图,其中有一个按钮,当按下该按钮时,应将地图置于用户当前位置的中心。我正在尝试使用 Swift 的 Combine 框架来实现这一点。我尝试通过在 Combine 的主题中添加一个@State
名为mapCenter
并分配给该属性的属性来解决此assign(to:on:)
问题,如下所示:
struct MapWithButtonView: View {
// What the current map view center should be.
@State var mapCenter = CLLocationCoordinate2D(latitude: 42.35843, longitude: -71.05977)
// A subject whose `send(_:)` method is being called from within the CenterButton view to center the map on the user's location.
private var centerButtonTappedPublisher = PassthroughSubject<Bool, Never>()
// A publisher that turns a "center button tapped" event into a coordinate.
private var centerButtonTappedCoordinatePublisher: AnyPublisher<CLLocationCoordinate2D?, Never> {
centerButtonTappedPublisher
.map { _ in LocationManager.default.currentUserCoordinate }
.eraseToAnyPublisher()
}
private var coordinatePublisher: AnyPublisher<CLLocationCoordinate2D, Never> {
Publishers.Merge(LocationManager.default.$initialUserCoordinate, centerButtonTappedCoordinatePublisher)
.replaceNil(with: CLLocationCoordinate2D(latitude: 42.35843, longitude: -71.05977))
.eraseToAnyPublisher()
}
private var cancellableSet: Set<AnyCancellable> = []
init() {
// This does not result in an update to the view... why not?
coordinatePublisher
.receive(on: RunLoop.main)
.handleEvents(receiveSubscription: { (subscription) in
print("Receive subscription")
}, receiveOutput: { output in
print("Received output: \(String(describing: output))")
}, receiveCompletion: { _ in
print("Receive completion")
}, receiveCancel: {
print("Receive cancel")
}, receiveRequest: { demand in
print("Receive request: \(demand)")
})
.assign(to: \.mapCenter, on: self)
.store(in: &cancellableSet)
}
var body: some View {
ZStack {
MapView(coordinate: mapCenter)
.edgesIgnoringSafeArea(.all)
CenterButton(buttonTappedPublisher: centerButtonTappedPublisher)
}
}
}
这MapView
是一个UIViewRepresentable
视图,如下所示:
struct MapView: UIViewRepresentable {
// The center of the map.
var coordinate: CLLocationCoordinate2D
func makeUIView(context: Context) -> MKMapView {
let mapView = MKMapView(frame: .zero)
mapView.showsUserLocation = true
return mapView
}
func updateUIView(_ view: MKMapView, context: Context) {
let span = MKCoordinateSpan(latitudeDelta: 0.02, longitudeDelta: 0.02)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
这CenterButton
是一个简单的按钮,如下所示:
struct CenterButton: View {
var buttonTappedPublisher: PassthroughSubject<Bool, Never>
var body: some View {
Button(action: {
self.buttonTappedPublisher.send(true)
}) {
Image(systemName: "location.fill")
.imageScale(.large)
.accessibility(label: Text("Center map"))
}
}
}
并且LocationManager
是ObservableObject
发布用户当前和初始位置的一个:
class LocationManager: NSObject, ObservableObject {
// The first location reported by the CLLocationManager.
@Published var initialUserCoordinate: CLLocationCoordinate2D?
// The latest location reported by the CLLocationManager.
@Published var currentUserCoordinate: CLLocationCoordinate2D?
private let locationManager = CLLocationManager()
static let `default` = LocationManager()
private override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.pausesLocationUpdatesAutomatically = true
locationManager.activityType = .other
locationManager.requestWhenInUseAuthorization()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedAlways, .authorizedWhenInUse:
NSLog("Location authorization status changed to '\(status == .authorizedAlways ? "authorizedAlways" : "authorizedWhenInUse")'")
enableLocationServices()
case .denied, .restricted:
NSLog("Location authorization status changed to '\(status == .denied ? "denied" : "restricted")'")
disableLocationServices()
case .notDetermined:
NSLog("Location authorization status changed to 'notDetermined'")
default:
NSLog("Location authorization status changed to unknown status '\(status)'")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// We are only interested in the user's most recent location.
guard let location = locations.last else { return }
// Use the location to update the location manager's published state.
let coordinate = location.coordinate
if initialUserCoordinate == nil {
initialUserCoordinate = coordinate
}
currentUserCoordinate = coordinate
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
NSLog("Location manager failed with error: \(error)")
}
// MARK: Helpers.
private func enableLocationServices() {
locationManager.startUpdatingLocation()
}
private func disableLocationServices() {
locationManager.stopUpdatingLocation()
}
}
不幸的是,上述方法不起作用。点击时,视图永远不会更新CenterButton
。我最终通过使用具有属性的ObservableObject
视图模型对象解决了这个问题@Published var mapCenter
,但是我不知道为什么我的初始解决方案使用@State
不起作用。@State
像我上面所做的那样更新有什么问题?
请注意,如果尝试重现此问题,您需要在文件中添加NSLocationWhenInUseUsageDescription
具有诸如“此应用需要访问您的位置”之类的值的键,Info.plist
以便能够授予位置权限。