0

我想使用swift 5编写一个供个人使用的地图应用程序(iOS)。我已经能够通过使用单个文件使其工作,但是代码看起来很乱,所以我决定使用多个文件并调用来自 ViewController 的函数。对于一个简单的地图视图,我已经使用以下代码实现了它:

//ViewController.swift
import UIKit
import Mapbox
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        mapInit()
        // Do any additional setup after loading the view.
    }
    
}
//mapInit.swift
import Foundation
import Mapbox
extension ViewController{
    func mapInit(){
        let mapView = MGLMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
         
        // Set the map’s center coordinate and zoom level.
        mapView.setCenter(CLLocationCoordinate2D(latitude: 59.31, longitude: 18.06), zoomLevel: 9, animated: false)
        view.addSubview(mapView)
    }
}

但我尝试使用 ViewController 文件更改地图样式

mapView.styleURL = MGLStyle.darkStyleURL

但我得到了

Use of unresolved identifier mapView

我也尝试使用

self.mapView.styleURL = MGLStyle.darkStyleURL

但现在我得到了

Value of type 'ViewController' has no member 'mapView'

我也尝试添加

var mapView: MGLMapView!

在 ViewController 的顶部,但现在它与消息一起崩溃

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

最后,我尝试从 ViewController.swift 初始化 mapView 并从 mapInit() 更改样式,但它什么也没改变。

有谁知道如何解决这个问题?

4

1 回答 1

0

如果你添加这个

import Mapbox
import UIKit
class ViewController: UIViewController, MGLMapViewDelegate {
var mapView: MGLMapView!
override func viewDidLoad() {
super.viewDidLoad()
mapView = MGLMapView(frame: view.bounds)
mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mapView.setCenter(CLLocationCoordinate2D(latitude: 0, longitude: 0), zoomLevel: 5, animated: false)
mapView.delegate = self
view.addSubview(mapView)

到您的主 ViewController,然后您可以通过extension ViewController.

于 2020-07-10T18:17:30.233 回答