LoginSignup
11
8

More than 3 years have passed since last update.

[SwiftUI memo] Buttonのカスタムスタイルを作成する (タップしたら縮小するアニメーションを付けてみる)

Posted at

アプリを作る時にボタンをカスタマイズするのはよくあります。

SwiftUIではボタンはButtonを使います。

Button(action: { ... }) { Text("Hello") }

タップした時のインタラクション・アニメーションはデフォルトで適用されます。
これはButtonStyle protocolに準拠したオブジェクトによって行われます。

つまり、ButtonStyleオブジェクトを自分で作ることによってタップした時のアニメーションやスタイルなどをカスタマイズすることができます。

例として、タップしたら縮小するButtonStyleを作ってみます。

 struct ShrinkButtonStyle: ButtonStyle {

    func makeBody(configuration: Self.Configuration) -> some View {

      let isPressed = configuration.isPressed

      return configuration.label
        .scaleEffect(x: isPressed ? 0.9 : 1, y: isPressed ? 0.9 : 1, anchor: .center)
        .animation(.spring(response: 0.2, dampingFraction: 0.9, blendDuration: 0))            
    }
  }

作ったStyleは.buttonStyle()で設定します。

 Button(action: {}) {
   Text("Hello")
     .padding(10)
     .background(Color.gray)
     .cornerRadius(8)
 }
 .buttonStyle(ShrinkButtonStyle())

Screen Recording 2019-10-05 at 16.50.49.gif

補足

スタイルを設定するにあたって、isPressed ? 0.9 : 1 のような記述をしています。
これはアニメーションを正しく実行するためにこのような記述の方が安定する様子。

if isPressed {
  return AnyView(...)
} else {
  return AnyView(...)
}

みたいな書き方でしっかり分けることもできると思うのですが、うまくいかなくなることが多い印象を受けました。

参考

11
8
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
11
8