Adding glow effect to UIButton - iOS

后端 未结 6 1986
一生所求
一生所求 2020-12-04 22:25

I have an UIButton which is a logo. This logo button will glow on forever but will stop glowing on touch.It is like a glowing animation.

Is there any suggestions?

6条回答
  •  攒了一身酷
    2020-12-04 23:18

    Swift 5

    1. Create UIView extension with the animation

    2. Use it on textfields, buttons, views (any subclass of UIView)

    Note: you may change values and play around to get the effect you need.

    UIView extension

    import UIKit
    
    extension UIView {
        enum GlowEffect: Float {
            case small = 0.4, normal = 2, big = 15
        }
    
        func doGlowAnimation(withColor color: UIColor, withEffect effect: GlowEffect = .normal) {
            layer.masksToBounds = false
            layer.shadowColor = color.cgColor
            layer.shadowRadius = 0
            layer.shadowOpacity = 1
            layer.shadowOffset = .zero
    
            let glowAnimation = CABasicAnimation(keyPath: "shadowRadius")
            glowAnimation.fromValue = 0
            glowAnimation.toValue = effect.rawValue
            glowAnimation.beginTime = CACurrentMediaTime()+0.3
            glowAnimation.duration = CFTimeInterval(0.3)
            glowAnimation.fillMode = .removed
            glowAnimation.autoreverses = true
            glowAnimation.isRemovedOnCompletion = true
            layer.add(glowAnimation, forKey: "shadowGlowingAnimation")
        }
    }
    

    How to use it:

    //TextField with border
    textField.doGlowAnimation(withColor: UIColor.red, withEffect: .big)
    
    //Label
    label.doGlowAnimation(withColor: label.textColor, withEffect: .small)
    
    //Button
    button.doGlowAnimation(withColor: UIColor.red, withEffect: .big)
    

提交回复
热议问题