0
2

More than 1 year has passed since last update.

【Swift】上がりながら消えていくアニメーションを実装する

Posted at

はじめに

いま作ってるアプリで「上がりながら消えていくアニメーション」を実装したので方法を共有します。

イメージ

Simulator Screen Recording - iPhone 12 - 2022-10-07 at 20.59.10.gif

実装

※関係ないところは省いてます
RxGesturepanGestureで指が離れた位置を取得します。
指が離れた位置にラベルを配置します。
UIView.animateでラベルにアニメーションを追加します。

view.rx
    .panGesture()
    .when(.ended)
    .subscribe(onNext: { position in
        self.makeCountUpLabel(position: position)
    })
    .disposed(by: disposeBag)

private func makeCountUpLabel(position: UIPanGestureRecognizer) {
    let label = UILabel(
        frame: CGRect(
            x: position.location(in: self.view).x,
            y: position.location(in: self.view).y,
            width: 50,
            height: 50
        )
    )
    label.textColor = .black
    label.text = "+1"

    self.view.addSubview(label)

    label.isHidden = true

    label.alpha = 1.0

    UIView.animate(withDuration: 2.0, delay: 0.0, options: [.curveEaseIn], animations: {
        label.isHidden = false
        label.center.y -= 100.0
        label.alpha = 0.0
    }) { _ in
        label.removeFromSuperview()
    }
}

おわり

UIViewのアニメーションを初めて触りました。
SwiftUIでのアニメーションよりできることの幅が広くて便利です

0
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
0
2