メインコンテンツへスキップ
見出し画像

[SwiftUI] モディファイアを作る

    【問題】
    モディファイアを作成してボタンに設定してみましょう。
    アプリ内でボタンの見た目を同じようにする時などに便利です。

    画像

    【回答】

    ① CustomModifier.swifファイルを作成する

    import SwiftUI
    
    struct textModifier: ViewModifier {
        
        func body(content: Content) -> some View {
            content
                .frame(width: 200, height: 50)
                .foregroundColor(.blue)
                .font(.largeTitle)
                .underline(color: .red)
        }
    }
    
    
    struct buttonModifier: ViewModifier {
        
        let bgColor : Color
        
        func body(content: Content) -> some View {
            content
                .frame(maxWidth: .infinity)
                .frame(height: 60)
                .foregroundColor(.white)
                .background(bgColor)
                .font(.largeTitle)
                .cornerRadius(10)
        }
    }
    

    ② 使用するビュー

    VStack {
                    
        Text("blue")
            .foregroundColor(.blue)
            .modifier(textModifier())
        Text("brown")
            .foregroundColor(.brown)
            .modifier(textModifier())
            
        Button(action: {
                   
        }, label: {
            Text("pink")
        })
        .modifier(buttonModifier(bgColor: .pink))
            
        Button(action: {
                   
        }, label: {
            Text("orange")
        })
        .modifier(buttonModifier(bgColor: .orange))
    
        Button(action: {
                   
        }, label: {
            Text("cyan")
        })
        .modifier(buttonModifier(bgColor: .cyan))
          
    }
    .padding()


     
     
    Objective-Cでのアプリ開発を10年以上。 なんだかんだとSwiftには手を出さずにいました。 が、プログラミングを教える機会があったため、ついにSwiftUIに手を出し始めました。 教材用に練習帳を作っています。 気になる点がありましたらご連絡くださいませー。

    あなたへのおすすめ