diff --git a/TZStackView/TZStackView.swift b/TZStackView/TZStackView.swift index 2fd77a8..7aea707 100755 --- a/TZStackView/TZStackView.swift +++ b/TZStackView/TZStackView.swift @@ -8,15 +8,6 @@ import UIKit -struct TZAnimationDidStopQueueEntry: Equatable { - let view: UIView - let hidden: Bool -} - -func ==(lhs: TZAnimationDidStopQueueEntry, rhs: TZAnimationDidStopQueueEntry) -> Bool { - return lhs.view === rhs.view -} - public class TZStackView: UIView { public var distribution: TZStackViewDistribution = .Fill { @@ -51,8 +42,6 @@ public class TZStackView: UIView { private var spacerViews = [UIView]() - private var animationDidStopQueueEntries = [TZAnimationDidStopQueueEntry]() - private var registeredKvoSubviews = [UIView]() private var animatingToHiddenViews = [UIView]() @@ -112,37 +101,40 @@ public class TZStackView: UIView { removeHiddenListener(view) view.hidden = false - - if let _ = view.layer.animationKeys() { - UIView.setAnimationDelegate(self) - animationDidStopQueueEntries.insert(TZAnimationDidStopQueueEntry(view: view, hidden: hidden), atIndex: 0) - UIView.setAnimationDidStopSelector("hiddenAnimationStopped") + + let hiddenAnimation: CAAnimation? + if let animationKeys = view.layer.animationKeys() { + let boundsKey = "bounds.size" + if animationKeys.indexOf(boundsKey) != nil { + hiddenAnimation = view.layer.animationForKey(boundsKey) + } else { + hiddenAnimation = nil + } } else { - didFinishSettingHiddenValue(view, hidden: hidden) + hiddenAnimation = nil } - } - } - - private func didFinishSettingHiddenValue(arrangedSubview: UIView, hidden: Bool) { - arrangedSubview.hidden = hidden - if let index = animatingToHiddenViews.indexOf(arrangedSubview) { - animatingToHiddenViews.removeAtIndex(index) - } - addHiddenListener(arrangedSubview) - } - - func hiddenAnimationStopped() { - var queueEntriesToRemove = [TZAnimationDidStopQueueEntry]() - for entry in animationDidStopQueueEntries { - let view = entry.view - if view.layer.animationKeys() == nil { - didFinishSettingHiddenValue(view, hidden: entry.hidden) - queueEntriesToRemove.append(entry) + + let animationFinishFunc = { [weak self, weak view] () in + view?.layer.hidden = hidden + if let selv = self, strongView = view { + if let index = selv.animatingToHiddenViews.indexOf(strongView) { + selv.animatingToHiddenViews.removeAtIndex(index) + } + selv.addHiddenListener(strongView) + } } - } - for entry in queueEntriesToRemove { - if let index = animationDidStopQueueEntries.indexOf(entry) { - animationDidStopQueueEntries.removeAtIndex(index) + + if let hiddenAnimation = hiddenAnimation { + let group = CAAnimationGroup() + group.animations = [] + group.delegate = TZFuncAnimationDelegate { _ in + animationFinishFunc() + } + group.tz_copyTiming(hiddenAnimation) + + view.layer.addAnimation(group, forKey: "TZSV-hidden-callback") + } else { + animationFinishFunc() } } }