はじめに
SwiftUIのUIコンポーネントには複数の書き方があります。
例えばButtonだと以下のような書き方があります。
Button {
} label: {
}
Button("") {
}
2個目の書き方はText
を省略することができます。
Labelでも同じような書き方ができるように拡張します。
実装
extension Label where Title == Text, Icon == Image {
init<T: StringProtocol>(_ title: T, icon: Image) {
self.init {
Text(title)
} icon: {
icon
}
}
}
使い方
Label("このように書くことができます", icon: Image(systemName: "volleyball.fill"))
おわり
1行で書けるようになりました。