swift - 在 Combine 的 `assign(to:on:)` 主题中分配给 @State 不会导致视图更新
问题描述
我有一个地图视图,其中有一个按钮,当按下该按钮时,应将地图置于用户当前位置的中心。我正在尝试使用 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
以便能够授予位置权限。
解决方案
新答案:
好的,我是一个组合新手,但它并没有让我离开,所以我尝试了又尝试......现在它可以工作了,即使在模拟器中也是如此。
问题是,您在 struct/Contentview 中完成了所有操作,而不是在一个单独的类中进行合并,该类发布您想要更改的值。
看一下这个:
class Model : ObservableObject {
@Published var mapCenter : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
// A subject whose `send(_:)` method is being called from within the CenterButton view to center the map on the user's location.
public 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
print ("new loc in pub: ", LocationManager.default.currentUserCoordinate)
return LocationManager.default.currentUserCoordinate
}
.eraseToAnyPublisher()
}
private var coordinatePublisher: AnyPublisher<CLLocationCoordinate2D, Never> {
Publishers.Merge(LocationManager.default.$initialUserCoordinate, centerButtonTappedCoordinatePublisher)
.replaceNil(with: CLLocationCoordinate2D(latitude: 2.0, longitude: 2.0))
.eraseToAnyPublisher()
}
private var cancellableSet: Set<AnyCancellable> = []
var cancellable: 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)
print(cancellableSet)
self.cancellable = self.coordinatePublisher.receive(on: DispatchQueue.main)
.assign(to: \.mapCenter, on: self)
}
}
struct ContentView: View {
@ObservedObject var model = Model()
var body: some View {
VStack {
MapView(coordinate: model.mapCenter)
.edgesIgnoringSafeArea(.all)
CenterButton(buttonTappedPublisher: model.centerButtonTappedPublisher)
}
}
}
struct MapView: UIViewRepresentable {
// The center of the map.
var coordinate: CLLocationCoordinate2D
let mapView = MKMapView(frame: .zero)
func makeUIView(context: Context) -> MKMapView {
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)
print("map new coordinate", coordinate)
view.setRegion(region, animated: true)
}
}
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()
enableLocationServices()
}
}
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")'")
()
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.
public func enableLocationServices() {
locationManager.startUpdatingLocation()
}
private func disableLocationServices() {
locationManager.stopUpdatingLocation()
}
}
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"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
旧答案:
好的,因为你没有给我们一个可复制的可重现的例子,我做了一个简单的例子。随意复制并使用它来解决您的问题。
struct MapView: UIViewRepresentable {
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: 1.02, longitudeDelta: 1.02)
let region = MKCoordinateRegion(center: coordinate, span: span)
view.setRegion(region, animated: true)
}
}
struct ContentView: View {
@State var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
var body: some View {
VStack {
Button(action: {
self.coordinate.latitude += 10
self.coordinate.longitude = 30
}) {
Text("new coordinate")
}
MapView(coordinate: coordinate)
}
}
}
推荐阅读
- reactjs - 如何迭代嵌套数组
- tensorflow - decode_png 返回 3 维问号的形状
- python-3.x - 这个models.Manager,get_by_natural_key类/函数到底发生了什么,我如何动态替换它?
- excel - Excel:有没有办法计算给定范围内的非空列数?
- javascript - 是否可以使用节点执行 AppKit 功能?
- kubernetes - 如何配置fluentbit仅发送错误日志
- node.js - res.download 方法是否读取内存中的整个文件?
- ios - 如果我只是特别需要一个,为什么要获取所有用户数据?
- r - WGCNA 为统计方法共享命名空间
- bash - Groovy:如何执行从詹金斯“带参数构建”中提取的 sh 命令