4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Snapchatのボタンみたいにタップ中に大きくなるUIButtonの作り方

Last updated at Posted at 2018-08-23

SnapChatみたいにフォーカス中だけ大きくなるUIButtonができたのでシェアします。

GIFイメージ-F5CC3A238CB3-1.gif

.touchDown で大きくして、.touchUpInside, .touchUpOutside, .touchCancel で小さくします。

IBActionでタップイベントを定義せずに、

button.setOnClickListener {[weak self] in
    self?.thinkUnique()
}

みたいな感じで使います。

import UIKit

class MicroInteractButton: UIButton {
    private var clickListener: (() -> Void)?

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupAnimation()
        adjustsImageWhenHighlighted = false
    }
    
    func setOnClickListener(_ completion: (() -> Void)?) {
        clickListener = completion
    }
    
    private func setupAnimation(){
        addTarget(self, action: #selector(pressed), for: [.touchDown])
        addTarget(self, action: #selector(released), for: [.touchUpInside, .touchUpOutside, .touchCancel])
    }
    
    @objc private func pressed(){
        expandAnimation()
    }
    
    @objc private func released(){
        shrinkAnimation()
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.clickListener?()
        }
    }
    
    private func expandAnimation() {
        let expand = CASpringAnimation(keyPath: "transform.scale")
        expand.duration = 0.2
        expand.fromValue = 1
        expand.toValue = 1.3
        expand.autoreverses = false
        expand.repeatCount = 1
        expand.initialVelocity = 0.8
        expand.damping = 1.0
        expand.fillMode = kCAFillModeForwards
        expand.isRemovedOnCompletion = false
        layer.bounds = self.bounds
        layer.contentsGravity = "center"
        layer.add(expand, forKey: "expand")
    }
    
    private func shrinkAnimation() {
        let shrink = CABasicAnimation(keyPath: "transform.scale")
        shrink.duration = 0.2
        shrink.fromValue = 1.3
        shrink.toValue = 1
        shrink.autoreverses = false
        shrink.repeatCount = 1
        shrink.fillMode = kCAFillModeForwards
        shrink.isRemovedOnCompletion = false
        layer.add(shrink, forKey: "shrink")
    }
}

gistにあげてます。
https://gist.github.com/kboy-silvergym/62de6540ee61d879ca584e707719e171

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?