LoginSignup
2
3

More than 3 years have passed since last update.

[SwiftUI]Buttonのカスタマイズ

Posted at

SwiftUIでButtonのカスタマイズ方法を調べました。
カスタマイズ方法はUIKitのUIButtonとだいぶ違ったので、試行錯誤に時間がかかりました。

どのようなボタンを作るか

  • 背景が塗りつぶしで角丸
  • シャドーがある
  • ボタンを押した時のエフェクトをつける

作成したもの

Playground
スクリーンショット 2020-08-08 11.52.12.png
  • 1つ目:角丸の通常ボタン
  • 2つ目:角丸の無効状態のボタン
  • 3つ目:角丸が完全な丸のボタン

実装方法

SwiftUIのButtonStyleを使います。
文字の内容・画像とそのpaddingについてはButtonStyleで共通化できませんでした。(paddingが共通化できないのはなんでだろう)

CustomButtonStyle.swift
struct CustomButtonStyle: ButtonStyle {

    @State var isEnabled: Bool  //ボタン有効・無効
    var cornerRadius: CGFloat   //角丸半径
    var color: Color            //通常Color
    var disabledColor: Color    //無効Color
    var textColor: Color        //テキストcolor

    func makeBody(configuration: Configuration) -> some View {
        let isPressed = configuration.isPressed
        let foregroundColor = isEnabled ? color : disabledColor
        return configuration.label
            .background(RoundedRectangleFill.init(cornerRadius: cornerRadius, fillColor: foregroundColor))
            .foregroundColor(textColor)
            .shadow(color: foregroundColor, radius: 5, x: 0, y: 0)
            .scaleEffect(x: isPressed ? 0.95 : 1, y: isPressed ? 0.95 : 1, anchor: .center)
            .animation(.spring(response: 0.2, dampingFraction: 0.9, blendDuration: 0))
    }

}

細かい実装はソースを見てください。

  • cornerRadiusに.infinityを設定すると、角丸が完全な丸になります。(スクショ3つ目のボタン)
  • backgroundにRoundRectangleベースの角丸塗りつぶしを設定しています
  • foregroundColorでテキスト・画像の色を設定しています
  • shadowで影を描画しています
  • scaleEffectとanimationでボタンを押した時のアニメーションを設定しています

ソース

こちらに置いてあります。

参考

https://developer.apple.com/documentation/swiftui/buttonstyle
https://developer.apple.com/documentation/swiftui/primitivebuttonstyle
https://medium.com/better-programming/how-to-build-and-customize-buttons-in-swiftui-448f5994022d
https://qiita.com/muukii/items/46125dced6be51ddb736
https://stackoverflow.com/questions/59169436/swiftui-buttonstyle-how-to-check-if-button-is-disabled-or-enabled
https://will.townsend.io/2019/an-intro-to-swiftui-button-styles

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