LoginSignup
6
8

More than 1 year has passed since last update.

SwiftUIのボタンを少し書きやすくする。

Last updated at Posted at 2022-07-01

なぜ?

従来のボタンの処理がみづらい。
全てのボタンの処理を一括で管理するために実験的にアプリに導入してみた。

一般的なボタンの使い方


 Button(action: {
            print("タップされたよ")
        }){
            Text("Tap me")
                .foregroundColor(Color.white)
                .frame(width: 200, height:200)
                .background(Color.red)
                .frame(width: 500, height: 500)
        }

今回の方法 (View.onButtonTap {})

Viewを拡張 + ViewModifierを使うことで行数を減らすことができ、アプリのボタンタップの処理を一括して管理できる。


struct ButtonTapModifier: ViewModifier {
    
    var onTapped: (() -> Void)?

    func body(content: Content) -> some View {
        Button(action: {
            self.onTapped?()
        }){
            content
        }
    }
}

extension View {
    public func onButtonTap(_ onTapped: (() -> Void)? = nil) -> some View {
        self.modifier(ButtonTapModifier(onTapped: onTapped))
    }
}

struct ContentView: View {
    var body: some View {
        Text("テスト")
            .foregroundColor(Color.white)
            .frame(width: 200, height:200)
            .background(Color.red)
            .onButtonTap {
                print("タップされたよ");
            }
            .frame(width: 500, height: 500)
    }
}

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