简体   繁体   中英

Keep track of UIView position during translation animation

I know this has been asked before but all the answers were provided in Objective C and I'm looking for a Swift solution. If I've missed an existing Swift solution, please let me know and I'll close this question.

This is how I'm animating view:

UIView.animate(withDuration: 10.0, animations: { () in
   let translateTransform = CGAffineTransform.init(translationX: 0.0, y: Constants.screenHeight)
   self.icon.transform = translateTransform
})

What I'd like to do is keep track of current frame position throughout the animation. Do I need to take a different approach to achieve that?

You may want to try this to get a view's frame during an animation:

let currentFrame = myView.layer.presentation()!.frame

That will get you the frame at the time the code runs so if you wanted a record of the frames throughout the animation you may want to use a Timer (previously NSTimer).

In this example the optional is force unwrapped so if you're not sure if it's nil or not you may want to use an if-let statement.

Hope this helps and let me know if you have any other problems.

UIView.frame is observable. Try to use KVO for the frame keyPath:

view.addObserver(self, forKeyPath:"frame", options:.new, context:nil)

override func observeValue(forKeyPath keyPath: String, ofObject object: Any, change: [String: id], context: UnsafeMutableRawPointer) {
    print("value of \(keyPath) changed: \(change[NSKeyValueChangeNewKey])")
}

KVO doesn't work for classes that don't extend NSObject.

In order to use key-value observing with a Swift class you should inherit from NSObject .

Add the dynamic modifier to any property you want to observe. More on dynamic : https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html#//apple_ref/doc/uid/TP40014216-CH4-ID57

class YourClass: NSObject {
    dynamic var view: UIView = ...
}

Full article on KVO: https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html#//apple_ref/doc/uid/TP40014216-CH7-XID_8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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