0
1

【SwiftUI】Labelを簡単に使えるように拡張する

Last updated at Posted at 2023-02-14

はじめに

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行で書けるようになりました。

0
1
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
0
1