如何将值从一个函数传递到另一个函数?

时间:2017-09-16 07:49:58

标签: ios swift xcode

我想将当前的位置坐标从func locationManager()传递到我的func viewDidLoad()我该如何通过?

let manager = CLLocationManager()
var myLocation: CLLocationCoordinate2D?
var location=0
var latPass: Double!
var longPass: Double!

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    var location=locations[0]
    let span:MKCoordinateSpan=MKCoordinateSpanMake(0.01, 0.01)
    var myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion=MKCoordinateRegionMake(myLocation, span)
    latPass=location.coordinate.latitude
    longPass=location.coordinate.longitude
}

当我打印 lat & func locationManager中的我得到了值,但是当我在viewDidLoad()中打印它时,我得到了

这是我的viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()

    print(latPass)
    print(longPass)

    let position = CLLocationCoordinate2D(latitude:latPass, longitude: longPass)
    let london = GMSMarker(position: position)
    london.title = "You"
    london.tracksViewChanges=true
    london.icon = UIImage(named: "currentLocation.png")
    london.map = mapView
    mapView.selectedMarker=london
}

我想我必须创建一个var的实例,但我找不到方法。

2 个答案:

答案 0 :(得分:1)

ViewDidLoad它是视图控制器调用的第一个方法,一旦被调用,其他方法也被调用。您需要在viewDidLOad类中设置委托。加载视图时这些参数保持为空,但是当调用它的委托方法将存储数据时,您将按方法获取它。

你需要这样:

override func viewDidLoad() {
    super.viewDidLoad()

    manager.delegate = self
}

然后这个方法执行它的东西:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    var location=locations[0]
    let span:MKCoordinateSpan=MKCoordinateSpanMake(0.01, 0.01)
    var myLocation:CLLocationCoordinate2D=CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
    let region:MKCoordinateRegion=MKCoordinateRegionMake(myLocation, span)
    latPass=location.coordinate.latitude
    longPass=location.coordinate.longitude
    print(latPass)
    print(longPass)
    /// Here you can set the positioning managing stuff, because lat long are showing.
   let position = CLLocationCoordinate2D(latitude:latPass, longitude: longPass)
   let london = GMSMarker(position: position)
   london.title = "You"
   london.tracksViewChanges=true
   london.icon = UIImage(named: "currentLocation.png")
   london.map = mapView
   mapView.selectedMarker=london
}

调用方法后,您可以看到控制台的输出。

答案 1 :(得分:0)

根据您的代码,您无法将值传递给viewDidLoad方法,因为在加载视图时viewDidLoad方法调用已完成,而didUpdateLocations是委托方法,因此需要一些时间称之为 null 的原因。

仍无法理解您想要激活的内容。更详细的代码将帮助您。