How to use ScrollViewReader for iOS 14+ with deployment target of iOS 13

Viewed 508

iOS 14 adds a new ScrollViewReader view that you can add into your views hierarchy under ScrollView or List to be able to scroll to a specific view by id. How can you add this when your deployment target is iOS 13 though, without duplicating your views hierarchy by wrapping it with if #available?

List {
    ScrollViewReader { reader in //FIXME: 'ScrollViewReader' is only available in iOS 14.0 or newer
        Section(header:
            Text("Header")
                .id(0)
        ) {
            ForEach(items) { item in
                ItemCell()
            }
        }
        
        //for an example
        if #available(iOS 14.0, *) {
            Button("Scroll to Top") {
                reader.scrollTo(0)
            }
        }
    }
}
1 Answers

Just define a separate ContentView for the "innards" of your ScrollView, then you can use if #available(iOS 14.0, *) to selectively include a ScrollViewReader:

if #available(iOS 14.0, *) {
    ScrollViewReader { reader in
        ContentView()
    }
} else {
    ContentView()
}
Related