I wanted to code a map app for personal use (iOS) using swift 5. I have already been able to make it working by using a single file, but the code looks like a mess, so I decided to use multiple files and just call functions from the ViewController. For a simple map view I already made it possible with this code:
//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)
}
}
but I tried to change the map style from the ViewController file using
mapView.styleURL = MGLStyle.darkStyleURL
but I got
Use of unresolved identifier mapView
I also tried to use
self.mapView.styleURL = MGLStyle.darkStyleURL
but now I got
Value of type 'ViewController' has no member 'mapView'
I also tried to add
var mapView: MGLMapView!
at the top of the ViewController but now it crashes with the message
Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Finally I tried to initialize the mapView from the ViewController.swift and change the style from the mapInit() but it changed nothing.
Does anyone know how to solve this problem?