我目前正在试验 MapKit 和 SpriteKit,但是我遇到了一个问题。
当我尝试将 map 坐标转换为我屏幕上的一个点(在我的 GameScene 中)时,我收到一个错误:Unexpectedly found nil while unwrapping an optional value
以下代码会产生错误,并且在(出于测试目的)点击屏幕时运行的函数中。
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))!
}
我的 map 在我运行应用程序时显示出来,但是在执行上述代码时没有任何反应。我认为我的问题出在我当前从 GameViewController 访问 map 的方式上,但我不确定如何修复它。
澄清一下:我的 map 是在我的 GameViewController 中声明的,我需要从我的 GameScene 访问它,以便我可以将坐标转换为 View 中的一个点。
注意:我可能只是错误地使用了 convert 函数。
游戏 View Controller :
@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!
实际上从未包含值。
关于ios - Swift MKMapView 在 GameScene 中返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46333324/