もくじ
どうもこんにちは。iOSをメインに開発しているロッキーカナイです。
近頃、【swift】緯度経度から距離を求める方法や【swift】緯度経度から方角を計算するなど地図関連の記事を書いていたのですが、地図といえばコンパスでしょ?!って事で、コンパスを作ってみましたので紹介します。
期待させちゃうと申し訳ないのですが、すごいシンプルです。
コード
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
// ロケーションマネージャ
var locationManager: CLLocationManager!
// コンパスの針
@IBOutlet weak var needleView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// ロケーションマネージャ生成
locationManager = CLLocationManager()
// ロケーションマネージャのデリゲート設定
locationManager.delegate = self
// 角度の取得開始
locationManager.startUpdatingHeading()
}
// 角度の更新で呼び出されるデリゲートメソッド
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
// コンパスの針の方向計算
needleView.transform = CGAffineTransform.init(rotationAngle: CGFloat(-newHeading.magneticHeading) * CGFloat.pi / 180)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) メソッドで角度を受け取り、北の位置を計算し、needleView(針)の回転をしてます。
ストーリーボード

コンパスの針のViewを作って、センターに制約をつけてます。
またそれを、ViewControllerのneedleViewに紐付けてます。
おわり

動画を載せようと思ったのですが、ごにょごにょごにょ・・。とりあえず、私の実機では北を指す事が確認できました。
実機でないと確認ができないので、端末でご確認ください。
ではー