0

I'm currently working on Custom ScrollView without ScrollView.

I don't want to add too many features, but I want to be able to scroll by dragging. I've searched the Internet, but all I can find are examples of wrapped ScrollView.

The code I'm working on is as follows(WIP code):

import SwiftUI

struct ContentView: View {
  @State private var yOffset: CGFloat = 0
  @State private var contentSize: CGSize = .zero

  var body: some View {
    CustomScrollView {
      ForEach(0..<100) { i in
        Text(
          "\(i)"
        )
        .frame(
          maxWidth: .infinity
        )
        .background(
          Color.green
        )
      }
      .offset(y: 0)
      .size(size: $contentSize)
    }
    .offset(y: 0)
  }
}

struct CustomScrollView<Content: View>: View {
  let content: Content

  init(@ViewBuilder content: () -> Content) {
    self.content = content()
  }

  var body: some View {
    self.content
  }
}

//==================================================
// For extension
//==================================================

struct ChildSizeReader<Content: View>: View {
  @Binding var size: CGSize

  let content: () -> Content
  var body: some View {
    // Remove ZStack from the existing answer.
    content().background(
      GeometryReader { proxy in
        Color.clear.preference(
          key: SizePreferenceKey.self,
          value: proxy.size
        )
      }
    )
    .onPreferenceChange(SizePreferenceKey.self) { preferences in
      self.size = preferences
    }
  }
}

struct SizePreferenceKey: PreferenceKey {
  typealias Value = CGSize
  static var defaultValue: Value = .zero

  static func reduce(value _: inout Value, nextValue: () -> Value) {
    _ = nextValue()
  }
}

extension View {
  func size(size: Binding<CGSize>) -> some View {
    ChildSizeReader(size: size) {
      self
    }
  }
}

As you can see in the attached image, the top of the content is missing.

I would like to adjust it so that the top is visible, but I don't know how to do that.

Note: The dragging and other processes will be implemented after the top is visible first.

Reference:

ios coder
  • 1
  • 4
  • 31
  • 91
shingo.nakanishi
  • 2,045
  • 2
  • 21
  • 55
  • 1
    This should be helpful https://stackoverflow.com/a/58708206/12299030 – Asperi Aug 19 '21 at 15:22
  • It is without ScrollView. I'll read it! Thank you. – shingo.nakanishi Aug 19 '21 at 15:26
  • @shingo.nakanishi: It is not an easy project! It needs deep understanding of SwiftUI and need lots of logical codes for optimising it without extra renders and also do not forget that Custom ScrollView needs a Custom LazyVStack or LazyHStack! Your Custom ScrollView would be unusable if you have no plan to make it lazy! Not easy project! but possible. I did not menationed about animation! It needs lots of code to make same animation as we get from SwfitUI ScrollView. I would say it is a multi mega difficult project. – ios coder Aug 19 '21 at 16:43

0 Answers0