Состояние восстановления MKMapView немного уменьшается - PullRequest
0 голосов
/ 13 ноября 2018

Когда состояние восстанавливается для mapView, оно немного уменьшается по сравнению с тем, которое было во время сохранения. Я создал приложение iOS Single View, содержащее только MKMapView, заполняющее весь вид, чтобы попытаться устранить эту проблему. Мои операторы печати отладки показывают, что значения карты сохраняются и восстанавливаются должным образом, но широта или долгота диапазона в конечном итоге изменяются. Чего мне не хватает?

EDIT:

Этот вопрос относится к той же теме, что и
MKMapView setRegion «привязывается» к предопределенным уровням масштабирования?
MKMapView показывает неправильно сохраненный регион

В качестве эксперимента я добавил переменную класса типа MKCoordinateRegion и назначил ей область чтения в методе decodeRestorableState. Также я добавил кнопку и обработчик действия в контроллер представления, который устанавливает область mapView в значение добавленной переменной. При нажатии на кнопку карта масштабируется в положение, которое ожидалось от восстановления. Мне странно, что координаты местоположения некорректно работают в методе decodeRestorableState, но те же координаты работают правильно в обработчике действия кнопки.

import UIKit
import MapKit

class ViewController: UIViewController {
    @IBOutlet weak var mapView: MKMapView!
}

extension MKMapView {
    override open func encodeRestorableState(with coder: NSCoder) {
        super.encodeRestorableState(with: coder)
        region.encodeRestorableState(with: coder)
        camera.encodeRestorableState(with: coder)
    }

    override open func decodeRestorableState(with coder: NSCoder) {
        super.decodeRestorableState(with: coder)
        region.decodeRestorableState(with: coder)
        camera.decodeRestorableState(with: coder)
    }
}

extension MKCoordinateRegion {
    private static let KEY_LATITUDE  = "Region.latitude"
    private static let KEY_LONGITUDE = "Region.longitude"
    private static let KEY_WIDTH     = "Region.spanWidth"
    private static let KEY_HEIGHT    = "Region.spanHeight"

    func encodeRestorableState(with coder: NSCoder) {
        coder.encode(center.latitude, forKey: MKCoordinateRegion.KEY_LATITUDE)
        coder.encode(center.longitude, forKey: MKCoordinateRegion.KEY_LONGITUDE)
        coder.encode(span.latitudeDelta, forKey: MKCoordinateRegion.KEY_HEIGHT)
        coder.encode(span.longitudeDelta, forKey: MKCoordinateRegion.KEY_WIDTH)
    }

    mutating func decodeRestorableState(with coder: NSCoder) {
        center.latitude = coder.decodeDouble(forKey: MKCoordinateRegion.KEY_LATITUDE)
        center.longitude = coder.decodeDouble(forKey: MKCoordinateRegion.KEY_LONGITUDE)
        span.latitudeDelta = coder.decodeDouble(forKey: MKCoordinateRegion.KEY_HEIGHT)
        span.longitudeDelta = coder.decodeDouble(forKey: MKCoordinateRegion.KEY_WIDTH)
    }
}

extension MKMapCamera {
    private static let KEY_ALTITUDE  = "Camera.altitude"
    private static let KEY_HEADING   = "Camera.heading"
    private static let KEY_PITCH     = "Camera.pitch"
    private static let KEY_LATITUDE  = "Camera.latitude"
    private static let KEY_LONGITUDE = "Camera.longitude"

    func encodeRestorableState(with coder: NSCoder) {
        coder.encode(altitude, forKey: MKMapCamera.KEY_ALTITUDE)
        coder.encode(heading, forKey: MKMapCamera.KEY_HEADING)
        coder.encode(Double(pitch), forKey: MKMapCamera.KEY_PITCH)
        coder.encode(centerCoordinate.latitude, forKey: MKMapCamera.KEY_LATITUDE)
        coder.encode(centerCoordinate.longitude, forKey: MKMapCamera.KEY_LONGITUDE)
    }

    func decodeRestorableState(with coder: NSCoder) {
        altitude = coder.decodeDouble(forKey: MKMapCamera.KEY_ALTITUDE)
        heading = coder.decodeDouble(forKey: MKMapCamera.KEY_HEADING)
        pitch = CGFloat(coder.decodeDouble(forKey: MKMapCamera.KEY_PITCH))
        centerCoordinate.latitude = coder.decodeDouble(forKey: MKMapCamera.KEY_LATITUDE)
        centerCoordinate.longitude = coder.decodeDouble(forKey: MKMapCamera.KEY_LONGITUDE)
    }
}

1 Ответ

0 голосов
/ 08 апреля 2019

Была такая же проблема.Обходным решением для меня было установить mapView.camera в viewDidAppear моего контроллера представления.

let mapCameraKey = "MapCameraKey"
var restoredCamera: MKMapCamera?

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    if let restoredCamera = restoredCamera {
        mapView.camera = restoredCamera
    }
}

override func encodeRestorableState(with coder: NSCoder) {
    super.encodeRestorableState(with: coder)

    coder.encode(mapView.camera, forKey: mapCameraKey)
}

override func decodeRestorableState(with coder: NSCoder) {
    super.decodeRestorableState(with: coder)

    restoredCamera = coder.decodeObject(forKey: mapCameraKey) as? MKMapCamera
}

...