gpt4 book ai didi

ios - 如何将 UILabel 连接到其他类

转载 作者:行者123 更新时间:2023-11-28 15:35:33 24 4
gpt4 key购买 nike

我在 View Controller 上有一个 UI 标签,在 nsobject 上有一个字符串 (accuracy)。我想将字符串放在不断更新的 uilabel 上,因为当您打印字符串时(accuracy)它会更新。有人能帮我吗 ?谢谢

class Home: UIViewController {

@IBOutlet weak var lbl_accuracy: UILabel!
}

class PBLocation: NSObject, CLLocationManagerDelegate {

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

if CLLocationManager.locationServicesEnabled() {

switch(CLLocationManager.authorizationStatus()) {

case .notDetermined, .restricted, .denied:
print("No access")

case .authorizedAlways, .authorizedWhenInUse:

let accuracy = String(format: "%.4f", (locations.last?.horizontalAccuracy)!)
print("accuracy = \(accuracy)")
}
} else {
print("Location services are not enabled")
}
}
}

最佳答案

您可以使用 delegate design pattern将定位精度发送到 Home VC。首先创建LocationUpdatable 协议(protocol) 并添加updateLocationAccuracy(_ accuracy: String) 函数。在 PBLocation 类中创建一个弱委托(delegate)对象,现在您可以通过 updateLocationAccuracy 方法将精度对象发送到 Home VC。最后确认 Home VC 中的 LocationUpdatable 协议(protocol)并实现 updateLocationAccuracy(_ accuracy: String) 函数,最重要的是设置 Home VC 的 LocationUpdatable 委托(delegate)对象的委托(delegate)。

protocol LocationUpdatable: class {
func updateLocationAccuracy(_ accuracy: String)
}

//Confirm to the LocationUpdatable
class Home: UIViewController, LocationUpdatable {

@IBOutlet weak var lbl_accuracy: UILabel!

let location = PBLocation()
var locationManager: CLLocationManager!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
locationManager = CLLocationManager()
locationManager.delegate = location
locationManager.requestAlwaysAuthorization()

location.delegate = self
}

func updateLocationAccuracy(_ accuracy: String) {
lbl_accuracy.text = accuracy
}
}

//Create a delegate object
class PBLocation: NSObject, CLLocationManagerDelegate {

weak var delegate: LocationUpdatable?

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

if CLLocationManager.locationServicesEnabled() {

switch(CLLocationManager.authorizationStatus()) {

case .notDetermined, .restricted, .denied:
print("No access")

case .authorizedAlways, .authorizedWhenInUse:

let accuracy = String(format: "%.4f", (locations.last?.horizontalAccuracy)!)
print("accuracy = \(accuracy)")
if let delegate = delegate {
delegate.updateLocationAccuracy(accuracy)
}
}
} else {
print("Location services are not enabled")
}
}
}

关于ios - 如何将 UILabel 连接到其他类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com