Last active
July 26, 2017 09:25
-
-
Save el-hoshino/41fd0c2a480669cae7a1da933ac1c3fb to your computer and use it in GitHub Desktop.
Swift でアニメーションの連続実行をしてみる話 ref: http://qiita.com/lovee/items/460cbb02a345e0ff7910
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let base = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) | |
base.backgroundColor = .white | |
PlaygroundPage.current.liveView = base | |
let view = UIView(frame: CGRect(x: 100, y: 100, width: 200, height: 200)) | |
view.backgroundColor = .blue | |
base.addSubview(view) | |
// アニメーションブロック | |
UIView.animate(eachBlockDuration: 1, eachBlockDelay: 0, eachBlockOptions: .curveEaseInOut, animationBlocks: | |
{ view.frame.origin = .zero }, | |
{ view.frame.size.width = 400 }, | |
{ view.frame.size.height = 400 } | |
) { (finished) in | |
print(finished) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private extension ArraySlice { | |
var startItem: Element { | |
return self[self.startIndex] | |
} | |
} | |
extension UIView { | |
private typealias `Self` = UIView | |
private static func animate(eachBlockDuration duration: TimeInterval, eachBlockDelay delay: TimeInterval, eachBlockOptions options: UIViewAnimationOptions, animationArraySlice: ArraySlice<() -> Void>, completion: ((_ finished: Bool) -> Void)?) { | |
let animation = animationArraySlice.startItem | |
UIView.animate(withDuration: duration, delay: delay, options: options, animations: animation) { (finished) in | |
let remainedAnimations = animationArraySlice.dropFirst() | |
if remainedAnimations.isEmpty { | |
completion?(finished) | |
} else { | |
Self.animate(eachBlockDuration: duration, eachBlockDelay: delay, eachBlockOptions: options, animationArraySlice: remainedAnimations, completion: completion) | |
} | |
} | |
} | |
public static func animate(eachBlockDuration duration: TimeInterval, eachBlockDelay delay: TimeInterval = 0, eachBlockOptions options: UIViewAnimationOptions = .curveEaseInOut, animationBlocks: (() -> Void)..., completion: ((_ finished: Bool) -> Void)? = nil) { | |
let isFinished = animationBlocks.isEmpty | |
guard isFinished == false else { | |
completion?(isFinished) | |
return | |
} | |
let animationArraySlice = ArraySlice(animationBlocks) | |
Self.animate(eachBlockDuration: duration, eachBlockDelay: delay, eachBlockOptions: options, animationArraySlice: animationArraySlice, completion: completion) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment