|
| 1 | +// |
| 2 | +// OnChange.swift |
| 3 | +// CachedAsyncImage |
| 4 | +// |
| 5 | +// Created by Dmitry Kononchuk on 23.11.2023. |
| 6 | +// Copyright © 2023 Dmitry Kononchuk. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import SwiftUI |
| 10 | + |
| 11 | +struct OnChange<Value>: ViewModifier where Value: Equatable { |
| 12 | + // MARK: - Public Properties |
| 13 | + |
| 14 | + let value: Value |
| 15 | + let isInitial: Bool |
| 16 | + let action: (_ oldValue: Value?, _ newValue: Value) -> Void |
| 17 | + |
| 18 | + // MARK: - Body Method |
| 19 | + |
| 20 | + func body(content: Content) -> some View { |
| 21 | + if #available(iOS 17.0, macOS 14.0, *) { |
| 22 | + content |
| 23 | + .onChange(of: value, initial: isInitial) { oldValue, newValue in |
| 24 | + action(oldValue, newValue) |
| 25 | + } |
| 26 | + } else { |
| 27 | + content |
| 28 | + .onChange(of: value) { newValue in |
| 29 | + action(nil, newValue) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +// MARK: - Ext. View |
| 36 | + |
| 37 | +extension View { |
| 38 | + /// Method overloading – onChange(of:initial:_:). |
| 39 | + /// Adds a modifier for this view that fires an action when a specific value changes. |
| 40 | + /// |
| 41 | + /// - Parameters: |
| 42 | + /// - value: The value to check against when determining whether to run the closure. |
| 43 | + /// - isInitial: Whether the action should be run when this view initially appears. |
| 44 | + /// - action: A closure to run when the value changes. |
| 45 | + /// - oldValue: The old value that failed the comparisoncheck |
| 46 | + /// (or the initial value when requested). |
| 47 | + /// - newValue: The new value that failed the comparison check. |
| 48 | + /// |
| 49 | + /// - Returns: A view that fires an action when the specified value changes. |
| 50 | + func onChange<Value>( |
| 51 | + of value: Value, |
| 52 | + isInitial: Bool = false, |
| 53 | + action: @escaping (_ oldValue: Value?, _ newValue: Value) -> Void |
| 54 | + ) -> some View where Value: Equatable { |
| 55 | + modifier(OnChange(value: value, isInitial: isInitial, action: action)) |
| 56 | + } |
| 57 | +} |
0 commit comments