Ios 如何从swift中的委托类方法将数据传递回ViewController?
在ViewController中,我初始化了Location.swift中的类Ios 如何从swift中的委托类方法将数据传递回ViewController?,ios,swift,Ios,Swift,在ViewController中,我初始化了Location.swift中的类Location,以便使用它的方法 在ViewDidLoad中,我调用Location中的第一个方法,该方法设置定位服务(权限等)。同样在Location中,还有来自CLLocationManagerDelegate的两个委派方法 ViewController看起来像(简化的!): Location.swift看起来像(简化了!): 我可以很容易地从initLocation()获取数据,因为我自己调用并定义了该方法。但
Location
,以便使用它的方法
在ViewDidLoad
中,我调用Location
中的第一个方法,该方法设置定位服务(权限等)。同样在Location中,还有来自CLLocationManagerDelegate的两个委派方法
ViewController看起来像(简化的!):
Location.swift看起来像(简化了!):
我可以很容易地从initLocation()
获取数据,因为我自己调用并定义了该方法。但是,如果我需要从locationManager
方法获取数据,而我没有调用该方法,该怎么办
如果你有任何问题,一定要问。我希望我已经充分解释了
干杯您可以尝试为位置创建新代理,如: 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文件:
地址协议
protocol LocationProtocol : class {
func initLocation()
}
地点:斯威夫特
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()
}
}
您可以尝试为位置创建新代理,如: 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文件:
地址协议
protocol LocationProtocol : class {
func initLocation()
}
地点:斯威夫特
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()
}
}
是否每次更新时都需要newHeading值,还是只想调用该类以获取newHeading的最新值?您应该使用。。。代表团!创建一个协议,例如
LocationDelegate
,并在每次更新时通过您的ViewController
@KotaBear233实现:)您是每次更新时都需要newHeading值,还是只想调用这个类来获取newHeading最新的值?您应该使用。。。代表团!创建一个协议,例如LocationDelegate
,并在每次更新时由您的ViewController
@KotaBear233实现:)谢谢。当您在协议定义名称后添加class关键字时,这意味着什么?如果删除“:class”,则会将协议标记为仅可由类使用。您的委托对象将出现此错误:“'weak'可能仅应用于类和类绑定的协议类型,而不是'LocationProtocol'。谢谢。在协议定义名称后添加class关键字意味着什么?如果删除“:class”,则会将协议标记为仅可由类使用。您将在委托对象上收到此错误:“'weak'可能仅应用于类和类绑定的协议类型,而不是'LocationProtocol'”。