Skip to content

Instantly share code, notes, and snippets.

@seit
Last active December 2, 2024 02:09
Show Gist options
  • Select an option

  • Save seit/356c3a643fd276a1b01a18ea255220d4 to your computer and use it in GitHub Desktop.

Select an option

Save seit/356c3a643fd276a1b01a18ea255220d4 to your computer and use it in GitHub Desktop.
iOSアプリでカルーセルを作ってみた 1
import SwiftUI
public struct PagingScrollView<Content: View>: UIViewRepresentable {
let content: () -> Content
let disScroll: (CGPoint) -> Void
let disScrollEnd: () -> Void
public init(
@ViewBuilder _ content: @escaping () -> Content,
disScroll: @escaping (CGPoint) -> Void,
disScrollEnd: @escaping () -> Void
) {
self.content = content
self.disScroll = disScroll
self.disScrollEnd = disScrollEnd
}
public func makeUIView(context: UIViewRepresentableContext<PagingScrollView>) -> UIScrollView {
let view = UIScrollView()
view.delegate = context.coordinator
let hostingController = UIHostingController(rootView: content())
hostingController.view.sizeToFit()
view.addSubview(hostingController.view)
view.contentSize = hostingController.view.bounds.size
view.isPagingEnabled = true
view.clipsToBounds = false
view.showsHorizontalScrollIndicator = false
view.addSubview(hostingController.view)
view.bounces = false;
NSLayoutConstraint.activate([
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
hostingController.view.widthAnchor.constraint(equalTo: view.widthAnchor),
])
context.coordinator.hostingController = hostingController
return view
}
public func updateUIView(_ uiView: UIScrollView, context: UIViewRepresentableContext<PagingScrollView>) {}
public func makeCoordinator() -> Coordinator {
Coordinator(disScroll: disScroll, disScrollEnd: disScrollEnd)
}
public class Coordinator: NSObject, UIScrollViewDelegate {
var hostingController: UIHostingController<Content>?
let disScroll: (CGPoint) -> Void
let disScrollEnd: () -> Void
init(
disScroll: @escaping (CGPoint) -> Void,
disScrollEnd: @escaping () -> Void
) {
self.disScroll = disScroll
self.disScrollEnd = disScrollEnd
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
disScroll(scrollView.contentOffset)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
disScrollEnd()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment