[英]How to fire event on specific image rotation?
我正在使用此代碼將myCompass
-ImageView與當前設備標題對齊。 (旋轉圖像以指向北方向-> 這是一個指南針 )
func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
let Heading = newHeading.trueHeading.toRadians
UIView.animate(withDuration: 0.5) {
self.myCompass.transform = CGAffineTransform(rotationAngle: CGFloat(-Heading))
}
}
這段代碼可以正常運行,但是正如您所看到的,我添加了一個小動畫,以使IMageView的旋轉看起來不那么難看。
問題:現在,如果myCompass
-view恰好指向北極,我想觸發一個事件。
if (Heading > -4 && Heading < 4) {
event()
}
->由於動畫的原因,我無法檢查heading
因為它可能需要約0.5 seconds
才能使指針精確指向北。
->我無法檢查航向並添加0.5-delay
因為航向可能會在這0.5 seconds
再次更改
所以對我的問題:
是否可以偵聽ImageView的某種特定旋轉事件?
還是有一些更優雅的方式來獲得這樣的結果?
也許像這樣的偽代碼:
myCompass.onOrientation(rotationAngleMin: 5, rotationAngleMax: -5, event)
func event() {
print("hurray")
}
您可以嘗試通過以下方法對圖像的transform屬性進行鍵值觀察:
myCompass.addObserver(self, forKeyPath: "transform", options: [.old, .new], context: nil)
然后按照以下方法觀察
override func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) {
if keyPath == "transform" {
// Check your updates here
}
}
希望它能工作!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.