Swift MKMapView 在 GameScene 中返回 nil

Swift MKMapView returning nil in GameScene

我目前正在尝试使用 MapKit 和 SpriteKit,但是我 运行 遇到了问题。

当我尝试将地图坐标转换为我屏幕上的一个点(在我的 GameScene 中)时,出现错误:Unexpectedly found nil while unwrapping an optional value

以下代码会产生错误,并且在点击屏幕时(出于测试目的)运行s 的函数中。 monster.position = (mapView?.convert(spawnLocation, toPointTo: view))!

monster 是在我的 GameScene 顶部声明的 SKSpriteNode。 spawnLocation 只是一组坐标(我检查过,它们应该在屏幕上可见)。 mapView 在我的 GameScene 顶部声明如下:var mapView = GameViewController().map(我相信我的问题出在这里)

检查 mapView 是否包含一个值,不会导致任何内容打印到控制台:

if (mapView != nil) {
        print("not nil")
        monster.position = (mapView?.convert(spawnLocation, toPointTo: view))!
}

我的地图在我 运行 应用程序时显示,但是当执行上述代码时没有任何反应。我认为我的问题出在我目前从 GameViewController 访问地图的方式上,但我不确定如何解决它。

澄清一下:我的地图是在我的 GameViewController 中声明的,我需要从我的 GameScene 访问它,以便我可以将坐标转换为视图中的一个点。

注意:我可能只是使用了错误的转换函数。

游戏视图控制器:

@IBOutlet var parentView: UIView!
@IBOutlet var map: MKMapView!
@IBOutlet var skview: SKView!

let locationManager = CLLocationManager()

override func viewDidLoad() {
    super.viewDidLoad()

    map.delegate = self
    map.showsScale = false
    map.showsPointsOfInterest = false
    map.showsUserLocation = true
    map.showsBuildings = true
    map.isZoomEnabled = false
    map.isScrollEnabled = false
    map.isPitchEnabled = false
    map.isRotateEnabled = false

    locationManager.requestWhenInUseAuthorization()
    if (CLLocationManager.locationServicesEnabled()) {

        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()

    }

    let region = MKCoordinateRegionMakeWithDistance((locationManager.location?.coordinate)!, 400, 400)
    map.setRegion(region, animated: false)

    parentView.addSubview(map)
    parentView.addSubview(skview)

    GIDSignIn.sharedInstance().uiDelegate = self

}

所以在继续处理我的问题后,我又看了看 this 问题(我已经尝试了答案中的解决方案 - 它没有用)。 我注意到我的问题可能是我试图从中访问 MKMapView/GameViewController 的场景不是第一个场景。 当我将以下内容添加到我的代码时,它打印了 nil:

print("view controller", self.gameViewController)

然后我查看了负责从第一个场景过渡到我遇到问题的场景的代码,并添加了一行:

let signedInTransition = SKTransition.fade(withDuration: 1)

let nextScene = GameScene(size: scene!.size)
nextScene.scaleMode = .aspectFill

nextScene.gameViewController = self.gameViewController /* ADDED THIS LINE */

scene?.view?.presentScene(nextScene, transition: signedInTransition)

原来我的问题是我的场景实际上没有 GameViewController 因此

let gameViewController:GameViewController!

实际上从未包含值。