0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

SwiftUIで標準Modifierを拡張する

0
Posted at

新バージョンのみで使える新機能を使いたい場合など、Viewであればそのままifでバージョンを切り分けられるがModifierではできない。自作Modifierの名前を標準Modifierと同じ名前にして、対応バージョンでは標準Modifierを、非対応バージョンでは自作Modifier(あるいは無効)を指定することで前方互換性を持たせられる。

例えばiOS26~のnavigationSubtitleをiOS18以下では自作で再現するなら以下のように書く。

extension View {
    @ViewBuilder
    func navigationTitle(_ title:String, _ subtitle:String) -> some View {
        if #available(iOS 26.0, *) {
            self
                .navigationTitle(title)
                .navigationSubtitle(subtitle)
        } else {
            self.toolbar {
                ToolbarItem(placement: .principal) {
                    VStack {
                        Text(title).font(.headline)
                        Text(subtitle).font(.subheadline)
                    }
                }
            }
        }
    }
}

注意点として、戻り値がなかったり全く同じ型だと、自作Modifier内で本来のModifierを呼び出す際に自分自身が呼ばれて無限再帰が発生してしまう。引数ラベルを省略せず、任意の名称にすることで回避可能。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?