Skip to content

Instantly share code, notes, and snippets.

@DaisukeNagata
Last active February 26, 2020 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DaisukeNagata/d5cfe64a0c6b0fa8af4c5c70a60e531e to your computer and use it in GitHub Desktop.
Save DaisukeNagata/d5cfe64a0c6b0fa8af4c5c70a60e531e to your computer and use it in GitHub Desktop.
SwiftUI_Horizontal_Infinity_ScrollView
import SwiftUI
struct ContentView: View {
@State private var text = ""
@State private var evnent = HorizontalEvent(forEachCount: 1)
var body: some View {
ZStack {
HorizontalScrollView(event: self.evnent, action: { tex in
self.evnent.forEachCount += Int(tex) ?? 0
self.text = self.evnent.forEachCount.description
})
Text(self.text)
}
}
}
class HorizontalEvent: ObservableObject {
var forEachCount: Int
init(forEachCount: Int) {
self.forEachCount = forEachCount
}
}
struct HorizontalScrollView: View {
var rect = CGRect()
var evnents: HorizontalEvent
let action: (_ tex: String) -> Void
private var scText = "無限スクロール"
@State private var index: Int = 0
@State private var offset: CGFloat = 0
init(event :HorizontalEvent, action: @escaping (String) -> Void) {
rect = UIScreen.main.bounds
self.evnents = event
self.action = action
}
var body: some View {
ScrollView(.horizontal,showsIndicators: false) {
HStack {
ForEach(0..<self.evnents.forEachCount, id: \.self) { i in
Text("\(self.scText)").offset(y: -20)
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
}
}
}
.content.offset(x: self.offset/2)
.frame(width: rect.width * CGFloat(self.evnents.forEachCount), alignment: .center)
.gesture(DragGesture()
.onChanged({ value in
self.offset = value.translation.width - self.rect.width * CGFloat(self.index)
})
.onEnded({ value in
let scrollThreshold = self.rect.width / 2
if value.predictedEndTranslation.width < -scrollThreshold {
self.index = min(self.index+1, self.evnents.forEachCount)
self.action("\(1)")
} else if value.predictedEndTranslation.width > scrollThreshold {
self.index = max(self.index-1, -self.evnents.forEachCount)
}
withAnimation {
self.offset = -self.rect.width * CGFloat(self.index)
}
})
)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment