【发布时间】:2020-05-10 03:36:22
【问题描述】:
我试图以标签上显示的 N、S、E、W、NE、SE、SW、NW 的形式向用户指示他所面对的方向。每当用户改变他的物理方向时,标签就会更新为当前方向。
有什么建议吗?
【问题讨论】:
标签: swift xcode core-location
我试图以标签上显示的 N、S、E、W、NE、SE、SW、NW 的形式向用户指示他所面对的方向。每当用户改变他的物理方向时,标签就会更新为当前方向。
有什么建议吗?
【问题讨论】:
标签: swift xcode core-location
Swift 5.2
您可以使用CoreLocation 框架来做到这一点。
CLLocationManagerDelegate协议CLLocationManager 的实例并将委托设置为selfCLLocationManager 开始更新标题didUpdateHeading
import CoreLocation
import UIKit
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var directionLabel: UILabel!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.startUpdatingHeading()
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
directionLabel.text = cardinalValue(from: newHeading.trueHeading)
}
func cardinalValue(from heading: CLLocationDirection) -> String {
switch heading {
case 0 ..< 22.5:
return "N"
case 22.5 ..< 67.5:
return "NE"
case 67.5 ..< 112.5:
return "E"
case 112.5 ..< 157.5:
return "SE"
case 157.5 ..< 202.5:
return "S"
case 202.5 ..< 247.5:
return "SW"
case 247.5 ..< 292.5:
return "W"
case 292.5 ..< 337.5:
return "NW"
case 337.5 ... 360.0:
return "N"
default:
return ""
}
}
}
代理的标题可以通过.magneticHeading 或.trueHeading 访问
磁航向
此属性中的值表示相对于 与地理北极不同的磁北极 极。值 0 表示设备指向磁北, 90 表示指向东方,180 表示指向南方,以此类推。 此属性中的值应始终有效。
真航向
此属性中的值表示相对于 地理北极。值 0 表示设备指向 正北,90 表示正东,180 表示正东 正南,等等。负值表示标题 无法确定。
【讨论】:
CLLocationManager.headingAvailable()检查您正在运行的任何设备上是否有可用的航向信息//返回布尔值
PlaygroundPage.current.needsIndefiniteExecution = true