简体   繁体   English

在标签Xcode 7 Swift 2中显示CLLocation

[英]Displaying CLLocation in label Xcode 7 Swift 2

hey all i am brand new into coding iOS apps, and find it rather enjoyable so far.. 嘿,我都是iOS编程应用程序的新手,到目前为止还算不错。

I am having an issue assigning lat and lng to a text field. 我在将lat和lng分配给文本字段时遇到问题。 I have been following along in a tutorial but it crapped out and most examples i have found are in objective C and not swift.. and the ones in swift aren't all the best.. 我一直在跟随一个教程,但是它被淘汰了,我发现的大多数例子都在目标C中,而不是swift ..而swift中的例子并不是最好的。

my ViewController is below: 我的ViewController如下:

import UIKit
import MapKit

class LocationVC: UIViewController, MKMapViewDelegate {

    @IBOutlet weak var map: MKMapView!
    @IBOutlet weak var latField: UITextField!
    @IBOutlet weak var lngField: UITextField!
    @IBOutlet weak var locateBtn: UIButton!
    @IBOutlet weak var saveBtn: UIButton!

    let regionRadius: CLLocationDistance = 500

    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        map.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    }

    override func viewDidAppear(animated: Bool) {
        locationAuthStatus()
    }

    func locationAuthStatus() {
        if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse {
            map.showsUserLocation = true
        } else {
            locationManager.requestWhenInUseAuthorization()
        }
    }

    func centerMapOnLocation(location: CLLocation) {
        let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, regionRadius * 1, regionRadius * 1)
        map.setRegion(coordinateRegion, animated: true)
    }

    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
        if let loc = userLocation.location {
            centerMapOnLocation(loc)
        }

        let latField = location.longitude
        let lngField = location.latitude
    }

}

So far the map is moving, works on my device but I have no idea how to get the coords to appear.. 到目前为止,地图正在移动,可以在我的设备上运行,但我不知道如何显示坐标。

Please forgive me if this is a noob question, but I just cant get this damn thing to go.. 如果这是一个菜鸟问题,请原谅我,但我实在无法接受。

Replace your mapView(_ :,didUpdatedUserLocation:) with this... 将您的mapView(_:,didUpdatedUserLocation :)替换为此...

func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
    if let loc = userLocation.location 
    {
        centerMapOnLocation(loc)

        self.latField.text = "\(loc.coordinate.latitude)"
        self.lngField.text = "\(loc.coordinate.longitude)"
    }
}

Note: If you only need show the lat/lng could be a better idea to use an UILabel instead of UITextFiel 注意:如果只需要显示经纬度,最好使用UILabel而不是UITextFiel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM