我是編程新手。 我發現了下面的代碼,它除了中心位置以外都做了一切(放大地圖,藍色點全部工作)。 如果我在模擬器(城市運行)中運行,藍色點就會從頁面運行。如何使「地圖上的中心位置」工作?
import UIKit
import MapKit
import CoreLocation
import Foundation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager?
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager!.delegate = self
map.showsUserLocation = true
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager!.startUpdatingLocation()
} else {
locationManager!.requestWhenInUseAuthorization()
}
}
private func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
print("NotDetermined")
case .restricted:
print("Restricted")
case .denied:
print("Denied")
case .authorizedAlways:
print("AuthorizedAlways")
case .authorizedWhenInUse:
print("AuthorizedWhenInUse")
locationManager!.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first!
let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500)
map.setRegion(coordinateRegion, animated: true)
locationManager?.stopUpdatingLocation()
locationManager = nil
}
}
爲什麼不在地圖視圖中使用'userTrackingMode'屬性? – xoudini
謝謝Xoudini我是編程新手,對userTrackingMode一無所知,所以我不知道如何使用它。 – Doug
當位置服務處於打開狀態時,'yourMapView.userTrackingMode = .follow'自動使用戶居中,請參閱[documentation](https://developer.apple.com/reference/mapkit/mkmapview/1616208-usertrackingmode)。 – xoudini