地图按钮刷新位置

时间:2015-10-17 13:27:51

标签: swift dictionary mapkit

我正在开发我的第一个快速iPad应用程序。到目前为止,我有一个基本的mapview,底部工具栏中有一个按钮,我想刷新一次,并在点击后聚焦到用户位置。

目前我有这段代码:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

var location: CLLocation!
let locationManager = CLLocationManager()

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var refresh: UIBarButtonItem!

@IBAction func refresh(sender: AnyObject) {

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)

    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.mapView.setRegion(region, animated: true)
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.locationManager.delegate = self

    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest

    self.locationManager.requestWhenInUseAuthorization()

    self.locationManager.startUpdatingLocation()

    self.mapView.showsUserLocation = true

}

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

// location delegate methods

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: 1, longitudeDelta: 1))

    self.mapView.setRegion(region, animated: true)

    self.locationManager.stopUpdatingLocation()

}

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

}

如何获取刷新按钮?我真的需要一些帮助,因为我是Swift / xcode的新手:)

谢谢

3 个答案:

答案 0 :(得分:5)

正如@Orkhan所说,你可以这样做。

如果你想做这个动作你只需简单地按住Ctrl键拖动到viewController并选择“Action”。

enter image description here

之后,您可以将代码添加到处理程序。

Hello, World!
===End-Of-Output===
\n

答案 1 :(得分:3)

尝试以下3行代码:

@IBAction func refresh(sender: AnyObject) {
    mapView.setCenterCoordinate(mapView.userLocation.coordinate, animated: true)
}

修改

检查以下内容:

你能看到方法左侧的点吗?

enter image description here

我想看看你的连接检查员。刷新按钮和refresh方法是否正确连接?

enter image description here

答案 2 :(得分:1)

您可以使用此功能更新您的位置:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    let location = locations.last as CLLocation

    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)        
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}

如果您的目标是iOS 8,则需要在Info.plist中添加NSLocationAlwaysUsageDescription密钥。