【问题标题】:MKMapView seems to be nil?MKMapView 似乎是零?
【发布时间】:2016-10-05 17:43:59
【问题描述】:

我是 Xcode 和 Swift 的新手,我正在尝试简单地制作一张显示用户当前位置并更新它的地图。到目前为止我有这个:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

    @IBOutlet weak var map: MKMapView!

    let locationManager = CLLocationManager()
    var mapp = MKMapView.self

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        if (CLLocationManager.locationServicesEnabled())
        {
            self.locationManager.delegate = self
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.locationManager.requestWhenInUseAuthorization()
            self.locationManager.startUpdatingLocation()
            self.map.showsUserLocation = true
        }
        else
        {
            print("Location services are not enabled")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func loadView() {
        //let camera = GMSCameraPosition.camera(withLatitude: 36.2108, longitude: -81.6774, zoom: 15.0)
        //let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        //mapView.isMyLocationEnabled = true
        //view = mapView
    }


    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
        self.map.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Errors: " + error.localizedDescription)
    }
}

我在情节提要中制作了一个 MapView,然后 CTRL 将其拖到文件中(因此 @IBOutlet 弱 var 映射:MKMapView!)。但是,当我将手机插入并模拟应用程序时,它给了我一个“在展开可选值时意外发现 nil”,并且在一些打印语句之后,我发现每当我引用 map 变量时都会发生这种情况。为什么是这样?谢谢!

【问题讨论】:

  • 您是否检查过应用的功能选项卡?地图应该在那里(默认情况下它是关闭的)。
  • 删除loadView 方法。这仅在您以编程方式创建视图时使用。使用故事板(或 NIB)时,您将配置代码放入 viewDidLoad,而不是 loadView
  • @Rob 是对的。删除loadView,它应该可以工作。
  • 哇,谢谢 Rob 的快速回答。有效!呜呼!它放大到我当前的位置,但是没有蓝点指示我在哪里?我将如何得到它?谢谢!
  • 糟糕,加载需要一点时间,但它终于出现了!感谢大家的帮助!

标签: ios swift xcode gps mapkit


【解决方案1】:

在原帖的cmets中,Rob回答了这个问题:

"
删除 loadView 方法。这仅在您以编程方式创建视图时使用。使用情节提要(或 NIB)时,您将配置代码放在 viewDidLoad 中,而不是 loadView 中。 ——罗布”

谢谢你,罗伯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-25
    • 2021-12-31
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    相关资源
    最近更新 更多