Skip to content

Instantly share code, notes, and snippets.

@egoryanukovich
Last active March 17, 2024 16:32
Show Gist options
  • Save egoryanukovich/a971674452a4145e45de0d92f12f2377 to your computer and use it in GitHub Desktop.
Save egoryanukovich/a971674452a4145e45de0d92f12f2377 to your computer and use it in GitHub Desktop.
custom ScrollView for iOS 15+16
struct CustomScrollView<Content: View>: View {
// MARK: - Private properties
private let axes: Axis.Set
private let showIndicators: Bool
private let isBouncesEnabled: Bool
@ViewBuilder private var content: () -> Content
// MARK: - Init
init(
axes: Axis.Set = .vertical,
showIndicators: Bool = false,
isBouncesEnabled: Bool = true,
content: @escaping () -> Content
) {
self.axes = axes
self.showIndicators = showIndicators
self.isBouncesEnabled = isBouncesEnabled
self.content = content
}
// MARK: - View
var body: some View {
if #available(iOS 16.0, *) {
newScrollView
} else {
oldScrollView
}
}
private var oldScrollView: some View {
ScrollView(axes, showsIndicators: showIndicators) {
content()
}
.onAppear {
guard !isBouncesEnabled else { return }
UIScrollView.appearance().bounces = false
}
.onDisappear {
UIScrollView.appearance().bounces = true
}
}
@available(iOS 16.0, *)
private var newScrollView: some View {
ScrollView(axes) {
content()
}
.scrollIndicators(showIndicators ? .visible : .hidden)
.onAppear {
guard !isBouncesEnabled else { return }
UIScrollView.appearance().bounces = false
}
.onDisappear {
UIScrollView.appearance().bounces = true
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment