【Xcode/SwiftUI】カスタムモディファイアの使い方

今回の内容

・SwiftUIでカスタムモディファイアを使ってみる

カスタムモディファイアを使う前のコード

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World!")
                .font(.largeTitle)
            ForEach(0..<5) { index in
                Button {
                    print("Button Tapped")
                } label: {
                    Text("Button\(index)")
                        .font(.largeTitle)
                        .frame(width: UIScreen.main.bounds.width/1.3, height: UIScreen.main.bounds.height/28, alignment: .center)
                        .padding()
                        .border(Color.black, width: 1.5)
                        .foregroundColor(.white)
                        .background(.orange)
                        .padding()
                }
            }
        }
    }
}

テキストにつけているModifierを他のViewでも繰返し使いたい、となった時などに予めカスタムモディファイアとしてモディファイアの雛形をつくっておくことで便利に活用できる & コードの可読性が上がります。


カスタムモディファイアを追加する

Command + Nで新しいSwiftFileを追加する

CustomButtonModifier内を以下のように実装

import SwiftUI

struct CustomButtonModifier: ViewModifier {
    let foregroundColor: Color // ボタンのテキストカラー
    let backgroundColor: Color // ボタンの背景色
    
    func body(content: Content) -> some View { // カスタムモディファイアの内容
        content
            .font(.largeTitle) // フォントを大きくする
            .frame(width: UIScreen.main.bounds.width/1.3, height: UIScreen.main.bounds.height/28, alignment: .center) // ボタンのフレームサイズ
            .padding()
            .border(Color.black, width: 1.5) // 枠線の色、太さ
            .foregroundColor(foregroundColor)
            .background(backgroundColor)
            .padding()
    }
}

カスタムモディファイアを使ったコード

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello World!")
                .font(.largeTitle)
            ForEach(0..<5) { index in
                Button {
                    print("Button Tapped")
                } label: {
                    Text("Button\(index)")
                        .modifier(CustomButtonModifier(foregroundColor: .white, backgroundColor: .orange))
                }
            }
        }
    }
}

モディファイアの内容を別ファイルに切り分けることでスッキリしましたね、結構便利なので覚えておきましょう。


この記事は役に立ちましたか?

はい
いいえ
貴重なフィードバックありがとうございます!