如何从swift中的委托类方法将数据传递回ViewController?

时间:2016-08-05 21:07:37

标签: ios swift

在ViewController中,我启动了一个类Location,它位于Location.swift中,以便使用它的方法。

ViewDidLoad中,我调用Location中设置位置服务(权限等)的第一个方法。同样在Location中,是来自CLLocationManagerDelegate的两个委托方法。

ViewController看起来像(简化!):

class ViewController: UIViewController {
     var location = Location();
     override func viewDidLoad() {
          location.initLocation();
          //when updated data from delegated method, i want to get data to here, in order to output it in UI labels,etc
     }
}

Location.swift看起来像(简化了!):

import CoreLocation

class Location: NSObject, CLLocationManagerDelegate{
      func initLocation(){
         ........
      }

      @objc func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading){
            //i want to send  newHeading data to viewController here
      }

}

我可以轻松地从initLocation()获取数据,因为我自己调用并定义了该方法。但是,如果我需要从locationManager方法获取数据,而我没有调用该数据呢?

请问您是否有任何疑问。我希望我已经充分解释了!

干杯

1 个答案:

答案 0 :(得分:0)

您可以尝试为Location创建新的委托,例如:

ViewController.swift

class ViewController: UIViewController, LocationDeleate {

    var location = Location()

    override func viewDidLoad() {

       location.deleagte = self
       //location.initLocation()
   }

   func initLocation() {

       //when updated data from delegated method, i want to get data to here, in order to output it in UI labels,etc
   }
}

然后创建一个新的协议swift文件:

LocationProtocol.swift

protocol LocationProtocol : class {
    func initLocation()
}

Location.swift

import CoreLocation

class Location: NSObject, CLLocationManagerDelegate{

    weak var delegate : LocationDelegate?

    @objc func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading){

        // send notification to parent view controller
        delegate?.initLocation()
   }
}