前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swift 视图抖动扩展二

Swift 视图抖动扩展二

作者头像
韦弦zhy
发布2018-09-11 12:48:56
8590
发布2018-09-11 12:48:56
举报

嗯。。。UIView 的 animation 方法里面的 options 还有个.repate,是的,就是动画重复,所以我们可以不用去自己算重复的动画次数。。so,使用这个扩展也是可以的

代码语言:javascript
复制
//
//  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?()
            })
        }
    }
  • 说实话啥,第一种扩展还是比较好理解也比较好写的。。。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.08.16 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档