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

More than 1 year has passed since last update.

【Swift】iOS16までのonChangeとiOS17からのonChangeを使い分ける

Last updated at Posted at 2023-12-07

始めに

iOS16 ~ 17に対応するアプリを開発してると、今まで使っていたonChangeが非推奨になったので16までのonChangeと17からのonChangeで使い分けられるようにしました。

使い分け

extension View {
    // MARK: - Methods
    @ViewBuilder
    func onChangeInteractivelyAvailable<T: Equatable>(_ index: T,
                                                     action: @escaping (T?, T) async -> Void
    ) -> some View {
        if #available(iOS 17.0, *) {
        // iOS17からのonChange
            onChange(of: index) { oldValue, newValue in
                Task {
                    await action(oldValue, newValue)
                }
            }
        } else {
        // iOS16までのonChange
            onChange(of: index) { newValue in
                Task {
                    await action(nil, newValue)
                }
            }
        }
    }
}

以下は、呼び出す時

.onChangeInteractivelyAvailable(hoge) {
    print($0) // Optionalなのでnilチェックする(oldValue)
    print($1) // newValue
}

まとめ

これで、メソッドを呼べばiOS16 ~ 17でonChangeを使い分けられます。

参考

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