Help us understand the problem. What is going on with this article?

【iOS】UIButtonに波紋エフェクトを付ける

Ripple effectが付いたUIButtonを紹介します。
ripple.gif

コード

タッチ発生時に座標を取り、円形のUIViewを拡大・うすめながら表示します。

import UIKit

class RippleButton: UIButton {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        drawRipple(touch: touches.first!)
    }
    private func drawRipple(touch: UITouch) {
        let rippleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        rippleView.layer.cornerRadius = 100
        rippleView.center = touch.location(in: self)
        rippleView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
        rippleView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.4)
        addSubview(rippleView)
        UIView.animate(
            withDuration: 0.5,
            delay: 0.0,
            options: UIView.AnimationOptions.curveEaseIn,
            animations: {
                rippleView.transform = CGAffineTransform(scaleX: 1, y: 1)
                rippleView.backgroundColor = .clear
            },
            completion: { (finished: Bool) in
                rippleView.removeFromSuperview()
            }
        )
    }
}

使い方

RippleButtonを使うだけです。
Storyboardから使う場合は、UIButtonを置いたあとにカスタムクラスを設定して下さい。
image.png
なお、以下のようにボタンを角丸などにする場合はclipsToBounds = trueを設定しないと波紋がはみ出ます。
image.png

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした