How to maintain swiftui code for different versions of iOS

34 Views Asked by At

is there a method to use conditional modificators based on iOS version? I'd like to avoid having duplicate code fore entire views. as in this example. I'd like to maintain app lower iOS versions, but use api for iOS 16 if available

so,I DO NOT want this:

if #available(iOS 16.0, *) {
    
    NavigationView {
        List {
            Section {
                Text("Item 1")
            }
            Section {
                Text("Item 2")
                Text("Item 3")
                Text("Item 4")
            }
            Section {
                Text("Item 5")
                Text("Item 6")
                Text("Item 7")
            }
        }
        .background(.pink)
        .scrollContentBackground(.hidden) //available from iOS16 and above
    }
} else {
    NavigationView {
        List {
            Section {
                Text("Item 1")
            }
            Section {
                Text("Item 2")
                Text("Item 3")
                Text("Item 4")
            }
            Section {
                Text("Item 5")
                Text("Item 6")
                Text("Item 7")
            }
        }
        .background(.pink)
        //.scrollContentBackground(.hidden)
    }
}

MY SOLUTION based upon link Benzy Neez and relative answers.

   struct HideScrollBackgroundIfAvailableIOS16Modifier: ViewModifier {
    func body(content: Content) -> some View {
        if #available(iOS 16, *) {
            content
                .scrollContentBackground(.hidden)
        } else {
            content
        }
    }
}


extension View {
    /// Hides background if iOS 16 available, in order to show the background
    func hideScrollBackgroundIfAvailableIOS16Modifier() -> some View {
        self.modifier(HideScrollBackgroundIfAvailableIOS16Modifier())
    }
}

usage

List {
//my code
}
.hideScrollBackgroundIfAvailableIOS16Modifier()
.myModifierWithBackgroundImage
0

There are 0 best solutions below