编写UIView动画功能,以动画特定时间的视图

时间:2016-01-05 14:17:31

标签: ios swift uiview uiviewanimation

如何通过发送视图,动画次数,应用动作函数和成功函数来重构代码以使其更紧凑

如果可以提出函数式编程解决方案,那将会很有帮助

typealias AnimateAction = UIView -> Void
typealias AnimateSuccess = Bool -> Void

func animateThreetimes(animatedView:UIView,animateAction:AnimateAction,animateSuccess:AnimateSuccess)
        {

        UIView.animateWithDuration(0.5, animations: { () -> Void in

            animateAction(animatedView)

            }) { (success) -> Void in

                UIView.animateWithDuration(1, animations: { () -> Void in

                    animateAction(animatedView)

                    }, completion: { (success) -> Void in

                        UIView.animateWithDuration(0.5, animations: { () -> Void in

                            animateAction(animatedView)

                            }, completion: { (success) -> Void in
                                animateSuccess(success)
                        })
                })
        }
    }

3 个答案:

答案 0 :(得分:1)

递归会做得很好:

        func animate(count: Int) {
            if count > 0 {
                UIView.animateWithDuration(0.2, animations: { () -> Void in
                    // do the animations
                    }, completion: { (_) -> Void in
                        self.animate(count-1);
                })
            }
        }

答案 1 :(得分:1)

你也可以这样做,以便更多地控制你传入的变量以及你想如何处理完成。此外,这可以满足您对问题的功能性解决方案的要求。

typealias AnimationAction = UIView -> Void
typealias AnimationSuccess = Bool -> Void

func animateView(view: UIView, animationAction: AnimationAction) -> (duration: NSTimeInterval, completionHandler: AnimationSuccess?) -> Void {

    // Return a function that takes a duration and a maybe completion handler

    return { duration, completionHandler in

        return UIView.animateWithDuration(duration, animations: {

            animationAction(view)

            }, completion: { finished in

                completionHandler?(finished) // Optional function only called if exists
        })
    }
}

// Just showing the mechanism

let durations = [0.5, 1, 0.5]

for index in 0..<durations.count {

    let view = UIView(frame: CGRectZero)
    let animationAction: AnimationAction = { view in

        print("View: \(view)")
    }

    let completionHandler: AnimationSuccess? = {

        if durations[index] == durations.last {
            return { finished in
                print(finished)
            }
        } else {
            return nil
        }
    }()

    animateView(view, animationAction: animationAction)(duration: durations[index], completionHandler: completionHandler)
}

答案 2 :(得分:0)

假设您想要一种可用于任意数量动画的通用方法......

你可以在函数调用中包含一个计数器变量,在你有动画时减少它,当它非零时,再次调用animate函数