簡體   English   中英

Swift MKMapView在GameScene中返回nil

[英]Swift MKMapView returning nil in GameScene

我目前正在嘗試使用MapKit和SpriteKit,但是遇到了問題。

當我嘗試將地圖坐標轉換為屏幕上的點(在我的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))!
}

當我運行該應用程序時,我的地圖就會顯示出來,但是執行上述代碼后什么也沒發生。 我認為我的問題是我目前從GameViewController訪問地圖的方式,但是我不確定如何解決它。

需要說明的是:地圖是在GameViewController中聲明的,我需要從GameScene訪問它,以便可以將坐標轉換為視圖中的點。

注意:我可能只是使用了convert函數錯誤。

GameViewController:

@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

}

因此,在繼續解決我的問題之后,我又看了這個問題(我已經嘗試了答案中的解決方案-沒用)。 我注意到我的問題可能是我嘗試從中訪問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!

從未實際包含任何值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM