Infinite4Pager

Infinite4Pager 是一个灵活且强大的 SwiftUI 组件,它提供了四个方向(上、下、左、右)的无限滚动功能。它非常适合创建图像画廊、卡片堆栈或任何需要在多个方向上进行无缝导航的内容。

请阅读使用 SwiftUI 开发无限四向滚动 Pager,以了解此库的实现原理和更多使用说明。

infinity4pager-demo1.mp4

特性

要求

安装

Swift Package Manager

您可以使用 Swift Package Manager 将 Infinite4Pager 添加到您的项目中。在 Xcode 中,转到 File > Swift Packages > Add Package Dependency 并输入存储库 URL

https://github.com/fatbobman/Infinite4Pager.git

使用方法

这是一个如何使用 Infinite4Pager 的基本示例

import SwiftUI
import Infinite4Pager

struct TestView: View {
  var body: some View {
    Infinite4Pager(
      initialHorizontalPage: 2,
      initialVerticalPage: 2,
      totalHorizontalPage: 5,
      totalVerticalPage: 5,
      enableClipped: false,
      enablePageVisibility: true,
      getPage: { h, v in
        PageView(h: h, v: v)
      }
    )
    .ignoresSafeArea()
  }
}

struct PageView: View {
  let h: Int
  let v: Int
  let images = ["img1", "img2", "img3", "img4", "img5"]
  @Environment(\.pagerCurrentPage) var mainPage
  @State var percent: Double = 0
  @State var isCurrent = false
  var body: some View {
    VStack {
      let index = abs((h + v) % (images.count - 1))
      Color.clear
        .overlay(
          Image(images[index])
            .resizable()
            .aspectRatio(contentMode: .fill)
            .overlay(
              VStack {
                Text("\(h),\(v)")
                Text("visibility \(percent)")
                Text("isCurrent:\(isCurrent)")
              }
              .font(.largeTitle)
              .foregroundStyle(.white)
              .padding()
              .background(
                RoundedRectangle(cornerRadius: 15)
                  .foregroundColor(.black)
              )
            )
        )
        .onPageVisible { percent in
          if let percent {
            self.percent = percent
          }
        }
        .task(id: mainPage) {
          if let mainPage {
            if mainPage.horizontal == h, mainPage.vertical == v {
              isCurrent = true
            }
          }
        }
        .clipped()
    }
  }
}

有关更多高级用法和自定义选项,请参阅文档。

自定义

Infinite4Pager 提供了几个自定义选项

页面可见性和数据管理

类似于 `onScrollVisibilityChange` 的视图修饰符,用于提供视图当前可见区域的比例。

  PageView()
   .onPageVisible { percent in
    if percent > 0.1 {
      // play video
    }
  }

环境变量 pagerCurrentPage 提供有关容器中当前视图的信息。

.task(id: mainPage) {
  if let mainPage {
    if mainPage.horizontal == h, mainPage.vertical == v {
      // load data , enable animation
    }
  }
}

贡献

欢迎贡献!请随时提交 Pull Request。

许可证

Infinite4Pager 在 MIT 许可证下可用。 有关更多信息,请参见 LICENSE 文件。