swift创建左右晃动动画

前提:设计师给了一个静态图,图片放到UIButton上了,现在的需求是图片能够左右晃动。swift代码如下


swift

效果如下:


晃动效果

代码如下:
    private lazy var buttonView : UIView = {
        let buttonV = UIView()
        buttonV.frame = CGRect(x: FMScreenWidth - 80, y: FMScreenHeight-navigationBarHeight-tabBarHeight-100, width: 70, height: 70)
        buttonV.backgroundColor = UIColor.clear
        return buttonV
    }()
    //View晃动效果方法
    func shakeAnimation(){
        //移除self.mineTopView.layer上的所有动画,可以避免多次重复添加
        self.buttonView.layer.removeAllAnimations()
        let momAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        momAnimation.fromValue = NSNumber(value: -0.2) //左幅度
        momAnimation.toValue = NSNumber(value: 0.2) //右幅度
        momAnimation.duration = 0.2
        momAnimation.repeatCount = HUGE //无限重复
        momAnimation.autoreverses = true //动画结束时执行逆动画
        momAnimation.isRemovedOnCompletion = false //切出此界面再回来动画不会停止
        momAnimation.delegate = self//CAAnimationDelegate 代理中有动画的开始和结束
        self.buttonView.layer.add(momAnimation, forKey: "centerLayer")
    }
    //MARK:悬浮按钮
    private lazy var suspensionButton : UIButton = {
        let button = UIButton(type: UIButton.ButtonType.custom)
        button.setImage(UIImage(named: "RedEnvelopes"), for: .normal)
        button.frame = CGRect(x: 0, y: 0, width: 70, height: 70)
        button.adjustsImageWhenHighlighted = false
        button.adjustsImageWhenDisabled = false
        button.addTarget(self, action: #selector(self.buttonAction), for: UIControl.Event.touchUpInside)
        
        return button
    }()
    //悬浮按钮点击事件
    @objc func buttonAction(){
        print("点击了")
        
        let urlString = NetworkManager().linkPamrms(path: PostPath.homeShareBtn.path, params:"")
        let webView = FMBaseWebController()
        webView.webViewUrl = urlString
        webView.isNeedHidden = true
        webView.yaoYingYouLi = true
        webView.isHiddenNavigation = false
        navigationController?.pushViewController(webView, animated: true)
    }

你可能感兴趣的:(swift创建左右晃动动画)