简体   繁体   English

如何在特定的图像旋转上触发事件?

[英]How to fire event on specific image rotation?

I'm using this code to align the myCompass -ImageView to the current device heading. 我正在使用此代码将myCompass -ImageView与当前设备标题对齐。 (Rotate the image to point in North direction --> it's a compass ) (旋转图像以指向北方向-> 这是一个指南针

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
    let Heading = newHeading.trueHeading.toRadians

    UIView.animate(withDuration: 0.5) {
        self.myCompass.transform = CGAffineTransform(rotationAngle: CGFloat(-Heading))
    }
}

This code is working quiet fine but as you can see I've added a small animation so that the rotation of the IMageView doesn't looks that ugly. 这段代码可以正常运行,但是正如您所看到的,我添加了一个小动画,以使IMageView的旋转看起来不那么难看。

Problem: Now I want to fire an event if the myCompass -view is pointing exactly to the north pole . 问题:现在,如果myCompass -view恰好指向北极,我想触发一个事件。

if (Heading > -4 && Heading < 4) {
  event()
}
  • --> Because of the animation I can not check the heading because it could take about 0.5 seconds till the needle exactly points to North. ->由于动画的原因,我无法检查heading因为它可能需要约0.5 seconds才能使指针精确指向北。

  • --> I can not check the heading & add a 0.5-delay because the heading could change within this 0.5 seconds again ->我无法检查航向并添加0.5-delay因为航向可能会在这0.5 seconds再次更改


SO to my question: 所以对我的问题:

Is it possible to listen for some kind of specific rotation event of an ImageView? 是否可以侦听ImageView的某种特定旋转事件?

Or is there some more elegant way to get a result like this? 还是有一些更优雅的方式来获得这样的结果?

Maybe something like this pseudo code: 也许像这样的伪代码:

myCompass.onOrientation(rotationAngleMin: 5, rotationAngleMax: -5, event) 
func event() {
  print("hurray")
}

You can try key-value observing on transform property of you image by: 您可以尝试通过以下方法对图像的transform属性进行键值观察:

myCompass.addObserver(self, forKeyPath: "transform", options: [.old, .new], context: nil)

and then observe it in the following method 然后按照以下方法观察

override func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) {
    if keyPath == "transform" {
        // Check your updates here

    }
}

Hope it works!! 希望它能工作!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM