嗯。。。UIView 的 animation 方法里面的 options 还有个.repate,是的,就是动画重复,所以我们可以不用去自己算重复的动画次数。。so,使用这个扩展也是可以的
//
// UIView+ZHYShake.swift
// UIViewShake
//
// Created by ZHY on 2017/8/16.
// Copyright © 2017年 ZHY. All rights reserved.
//
import UIKit
/// 抖动方向
///
/// - horizontal: 水平抖动
/// - vertical: 垂直抖动
public enum ZHYShakeDirection: Int {
case horizontal
case vertical
}
extension UIView {
/// ZHY 扩展UIView增加抖动方法
///
/// - Parameters:
/// - direction: 抖动方向 默认水平方向
/// - times: 抖动次数 默认5次
/// - interval: 每次抖动时间 默认0.1秒
/// - offset: 抖动的偏移量 默认2个点
/// - completion: 抖动结束回调
public func shake2(direction: ZHYShakeDirection = .horizontal, times: Int = 5, interval: TimeInterval = 0.1, offset: CGFloat = 2, completion: (() -> Void)? = nil) {
//设置一下重复动画平移的两个变换
var firstTransform: CGAffineTransform? = nil
var lastTransform: CGAffineTransform? = nil
//判断下方向
switch direction {
case .horizontal:
firstTransform = CGAffineTransform(translationX: offset, y: 0)
lastTransform = CGAffineTransform(translationX: -offset, y: 0)
case .vertical:
firstTransform = CGAffineTransform(translationX: 0, y: offset)
lastTransform = CGAffineTransform(translationX: 0, y: -offset)
}
//这是开始的变换
self.transform = firstTransform!
//options: [.repeat, .autoreverse] 表示重复加动画回路
UIView.animate(withDuration: interval, delay: 0, options: [.repeat, .autoreverse], animations: {
//重复次数就是我们的times呗
UIView.setAnimationRepeatCount(Float(times))
// 开始变换完了,就改个变换方式咯
self.transform = lastTransform!
}) { (complet) in
UIView.animate(withDuration: interval, animations: {
self.layer.setAffineTransform(CGAffineTransform.identity)
}, completion: { (complet) in
completion?()
})
}
}
- 说实话啥,第一种扩展还是比较好理解也比较好写的。。。