
[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()