最后我想通了。实际上,叠加层没有更新不是由于setNeedsDisplayInMapRect
. 经过几次检查后,我发现这setNeedsDisplayInMapRect
实际上导致了运行drawMapRect:zoomScale:inContext:
,但是,默认重绘会以某种方式生成相同的平铺图像。我猜这可能是由于 MKTileOverlayRender 的一些内部缓存。
我的解决方案是将MKTileOverlayRender
, 和在新类中子类化:
override func canDrawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale) -> Bool {
let tilePath = self.tilePathForMapRect(mapRect, andZoomScale: zoomScale)
let tilePathString = stringForTilePath(tilePath)
if let _ = self.cache.objectForKey(tilePathString) {
return true
} else {
let tileOverlay = self.overlay as! MKTileOverlay
tileOverlay.loadTileAtPath(tilePath, result: {
data, error in
if error == nil && data != nil {
if let image = UIImage(data: data!) {
self.cache.setObject(image, forKey: tilePathString)
self.setNeedsDisplayInMapRect(mapRect, zoomScale: zoomScale)
}
}
})
return false
}
}
override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) {
let tilePath = self.tilePathForMapRect(mapRect, andZoomScale: zoomScale)
let tilePathString = stringForTilePath(tilePath)
if let image = self.cache.objectForKey(tilePathString) as? UIImage {
CGContextDrawImage(context, self.rectForMapRect(mapRect), image.CGImage)
} else {
super.setNeedsDisplayInMapRect(mapRect, zoomScale: zoomScale)
}
self.cache.removeObjectForKey(tilePathString)
}