【问题标题】:How can I implement PageView in SwiftUI?如何在 SwiftUI 中实现 PageView?
【发布时间】:2020-02-11 17:52:50
【问题描述】:

我是 SwiftUI 的新手。我有三个视图,我希望它们在 PageView 中。我想像页面浏览一样通过滑动来移动每个视图,并且我希望小点指示我在哪个视图中。

【问题讨论】:

  • 尝试使用UICollectionView。这是一个很棒的教程:youtube.com/watch?v=a5yjOMLBfSc
  • SwiftUIX 有一个 UIPageViewController 的 SwiftUI 包装器 - 请参阅 PaginatedViewsContent.swift
  • 请查看this。它是纯 SwiftUI,因此我发现生命周期更易于管理。此外,您可以在其中编写任何自定义 SwiftUI 代码。
  • 对于寻呼机,请查看this

标签: ios swift swiftui


【解决方案1】:

SwiftUI 3

在 iOS 15 中引入了新的 TabViewStyleCarouselTabViewStyle仅限 watchOS)。

此外,我们现在可以更轻松地设置样式:

.tabViewStyle(.page)

SwiftUI 2

现在在 SwiftUI 2 / iOS 14 中有一个原生的 UIPageViewController 等价物。

要创建分页视图,请将.tabViewStyle 修饰符添加到TabView 并传递PageTabViewStyle

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            TabView {
                FirstView()
                SecondView()
                ThirdView()
            }
            .tabViewStyle(PageTabViewStyle())
        }
    }
}

您还可以控制分页点的显示方式:

// hide paging dots
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))

您可以在此链接中找到更详细的说明:


垂直变体

TabView {
    Group {
        FirstView()
        SecondView()
        ThirdView()
    }
    .rotationEffect(Angle(degrees: -90))
}
.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
.rotationEffect(Angle(degrees: 90))

自定义组件

如果你厌倦了每次传递tabViewStyle,你可以创建自己的PageView

注意: iOS 14.0 中的 TabView 选择工作方式不同,这就是我使用两个 Binding 属性的原因:selectionInternalselectionExternal。从 iOS 14.3 开始,它似乎只使用了一个 Binding。但是,您仍然可以从修订历史中访问原始代码。

struct PageView<SelectionValue, Content>: View where SelectionValue: Hashable, Content: View {
    @Binding private var selection: SelectionValue
    private let indexDisplayMode: PageTabViewStyle.IndexDisplayMode
    private let indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode
    private let content: () -> Content

    init(
        selection: Binding<SelectionValue>,
        indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic,
        indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode = .automatic,
        @ViewBuilder content: @escaping () -> Content
    ) {
        self._selection = selection
        self.indexDisplayMode = indexDisplayMode
        self.indexBackgroundDisplayMode = indexBackgroundDisplayMode
        self.content = content
    }

    var body: some View {
        TabView(selection: $selection) {
            content()
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: indexDisplayMode))
        .indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: indexBackgroundDisplayMode))
    }
}

extension PageView where SelectionValue == Int {
    init(
        indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic,
        indexBackgroundDisplayMode: PageIndexViewStyle.BackgroundDisplayMode = .automatic,
        @ViewBuilder content: @escaping () -> Content
    ) {
        self._selection = .constant(0)
        self.indexDisplayMode = indexDisplayMode
        self.indexBackgroundDisplayMode = indexBackgroundDisplayMode
        self.content = content
    }
}

现在你有一个默认的PageView

PageView {
    FirstView()
    SecondView()
    ThirdView()
}

可以定制:

PageView(indexDisplayMode: .always, indexBackgroundDisplayMode: .always) { ... }

或提供selection:

struct ContentView: View {
    @State var selection = 1

    var body: some View {
        VStack {
            Text("Selection: \(selection)")
            PageView(selection: $selection, indexBackgroundDisplayMode: .always) {
                ForEach(0 ..< 3, id: \.self) {
                    Text("Page \($0)")
                        .tag($0)
                }
            }
        }
    }
}

【讨论】:

  • 如何垂直滚动?
  • @Dictator 我更新了我的答案,添加了垂直变体。
  • 以优雅的 SwiftUI 方式给出了很好的答案。
  • 这非常好用,谢谢!奇怪的是他们没有为此创建单独的视图类型,因为它在语义上不是标签视图。
  • 嘿@pawello2222,很棒的代码!使用 swifty 语法很好地实现。然而,到目前为止,当不使用ForEach 循环时,指示点不会随所选视图更新。如果我手动输入:MyView(text: message[0]) ... MyView(text: message[n]);无论我滑动到哪个视图,指示器都保持在index[0]
【解决方案2】:

页面控制

struct PageControl: UIViewRepresentable {
    var numberOfPages: Int
    @Binding var currentPage: Int
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIView(context: Context) -> UIPageControl {
        let control = UIPageControl()
        control.numberOfPages = numberOfPages
        control.pageIndicatorTintColor = UIColor.lightGray
        control.currentPageIndicatorTintColor = UIColor.darkGray
        control.addTarget(
            context.coordinator,
            action: #selector(Coordinator.updateCurrentPage(sender:)),
            for: .valueChanged)

        return control
    }

    func updateUIView(_ uiView: UIPageControl, context: Context) {
        uiView.currentPage = currentPage
    }

    class Coordinator: NSObject {
        var control: PageControl

        init(_ control: PageControl) {
            self.control = control
        }
        @objc
        func updateCurrentPage(sender: UIPageControl) {
            control.currentPage = sender.currentPage
        }
    }
}

您的页面浏览量

struct PageView<Page: View>: View {
    var viewControllers: [UIHostingController<Page>]
    @State var currentPage = 0
    init(_ views: [Page]) {
        self.viewControllers = views.map { UIHostingController(rootView: $0) }
    }

    var body: some View {
        ZStack(alignment: .bottom) {
            PageViewController(controllers: viewControllers, currentPage: $currentPage)
            PageControl(numberOfPages: viewControllers.count, currentPage: $currentPage)
        }
    }
}

你的页面视图控制器


struct PageViewController: UIViewControllerRepresentable {
    var controllers: [UIViewController]
    @Binding var currentPage: Int
    @State private var previousPage = 0

    init(controllers: [UIViewController],
         currentPage: Binding<Int>)
    {
        self.controllers = controllers
        self._currentPage = currentPage
        self.previousPage = currentPage.wrappedValue
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    func makeUIViewController(context: Context) -> UIPageViewController {
        let pageViewController = UIPageViewController(
            transitionStyle: .scroll,
            navigationOrientation: .horizontal)
        pageViewController.dataSource = context.coordinator
        pageViewController.delegate = context.coordinator

        return pageViewController
    }

    func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
        guard !controllers.isEmpty else {
            return
        }
        let direction: UIPageViewController.NavigationDirection = previousPage < currentPage ? .forward : .reverse
        context.coordinator.parent = self
        pageViewController.setViewControllers(
            [controllers[currentPage]], direction: direction, animated: true) { _ in {
            previousPage = currentPage
        }
    }

    class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
        var parent: PageViewController

        init(_ pageViewController: PageViewController) {
            self.parent = pageViewController
        }

        func pageViewController(
            _ pageViewController: UIPageViewController,
            viewControllerBefore viewController: UIViewController) -> UIViewController? {
            guard let index = parent.controllers.firstIndex(of: viewController) else {
                return nil
            }
            if index == 0 {
                return parent.controllers.last
            }
            return parent.controllers[index - 1]
        }

        func pageViewController(
            _ pageViewController: UIPageViewController,
            viewControllerAfter viewController: UIViewController) -> UIViewController? {
            guard let index = parent.controllers.firstIndex(of: viewController) else {
                return nil
            }
            if index + 1 == parent.controllers.count {
                return parent.controllers.first
            }
            return parent.controllers[index + 1]
        }

        func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
            if completed,
                let visibleViewController = pageViewController.viewControllers?.first,
                let index = parent.controllers.firstIndex(of: visibleViewController) {
                parent.currentPage = index
            }
        }
    }
}

假设您有这样的视图

struct CardView: View {
    var album: Album
    var body: some View {
        URLImage(URL(string: album.albumArtWork)!)
            .resizable()
            .aspectRatio(3 / 2, contentMode: .fit)
    }
}

你可以像这样在你的主 SwiftUI 视图中使用这个组件。

PageView(vM.Albums.map { CardView(album: $0) }).frame(height: 250)

【讨论】:

  • 能否告诉我如何在 PageView 中传递多个视图([/*准备一个 swiftUI 视图并在此处传递它。*/])我尝试但出现错误
  • @FarhanAmjad 如果我在页面控件之前或之后添加if 语句,类似if currentPage == 1 { ... } 的内容会中断分页。我在这里为此创建了一个问题:stackoverflow.com/questions/59448446/… - 任何帮助将不胜感激,谢谢!
  • 感谢您的出色回答,我称之为 PageView([Text("Test 1") , Text("Test 2")]).frame(height: 250) 但 swape 不起作用,可以你帮我
  • vm.Albums 部分是什么样的?是您传递给 PageView 的数据吗?
  • @BrodyHigby 是的。它的一系列专辑
【解决方案3】:

SwiftUI 1 & 2(带有私有方法)

警告:以下答案使用不公开可见的私有 SwiftUI 方法(如果您知道 where to look,您仍然可以访问它们)。但是,它们没有正确记录并且可能不稳定。使用它们需要您自担风险。

在浏览 SwiftUI 文件时,我偶然发现了自 iOS 13 起似乎可用的_PagingView

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct _PagingView<Views> : SwiftUI.View where Views : Swift.RandomAccessCollection, Views.Element : SwiftUI.View, Views.Index : Swift.Hashable

这个视图有两个初始化器:

public init(config: SwiftUI._PagingViewConfig = _PagingViewConfig(), page: SwiftUI.Binding<Views.Index>? = nil, views: Views)
public init(direction: SwiftUI._PagingViewConfig.Direction, page: SwiftUI.Binding<Views.Index>? = nil, views: Views)

我们还有_PagingViewConfig:

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct _PagingViewConfig : Swift.Equatable {
  public enum Direction {
    case vertical
    case horizontal
    public static func == (a: SwiftUI._PagingViewConfig.Direction, b: SwiftUI._PagingViewConfig.Direction) -> Swift.Bool
    public var hashValue: Swift.Int {
      get
    }
    public func hash(into hasher: inout Swift.Hasher)
  }
  public var direction: SwiftUI._PagingViewConfig.Direction
  public var size: CoreGraphics.CGFloat?
  public var margin: CoreGraphics.CGFloat
  public var spacing: CoreGraphics.CGFloat
  public var constrainedDeceleration: Swift.Bool
  public init(direction: SwiftUI._PagingViewConfig.Direction = .horizontal, size: CoreGraphics.CGFloat? = nil, margin: CoreGraphics.CGFloat = 0, spacing: CoreGraphics.CGFloat = 0, constrainedDeceleration: Swift.Bool = true)
  public static func == (a: SwiftUI._PagingViewConfig, b: SwiftUI._PagingViewConfig) -> Swift.Bool
}

现在,我们可以创建一个简单的_PagingView

_PagingView(direction: .horizontal, views: [
    AnyView(Color.red),
    AnyView(Text("Hello world")),
    AnyView(Rectangle().frame(width: 100, height: 100))
])

这是另一个更自定义的示例:

struct ContentView: View {
    @State private var selection = 1
    
    var body: some View {
        _PagingView(
            config: _PagingViewConfig(
                direction: .vertical,
                size: nil,
                margin: 10,
                spacing: 10,
                constrainedDeceleration: false
            ),
            page: $selection,
            views: [
                AnyView(Color.red),
                AnyView(Text("Hello world")),
                AnyView(Rectangle().frame(width: 100, height: 100))
            ]
        )
    }
}

【讨论】:

  • 我可以假设这不会在 App Store 应用程序中被接受吗?
  • @iSpain17 TBH 我真的不知道——我自己从未尝试过。我认为它不会被接受,因为它使用私有的无证方法,但我不是 100% 确定。这可能会对您有所帮助:How does Apple know you are using private API?
【解决方案4】:

对于面向 iOS 14 及更高版本的应用程序,@pawello2222 建议的答案应该被认为是正确的答案。我现在已经在两个应用程序中尝试过,效果很好,代码很少。

我已经将提议的概念包装在一个结构中,该结构可以提供两个视图以及一个项目列表和一个视图构建器。可以找到here。代码如下所示:

@available(iOS 14.0, *)
public struct MultiPageView: View {
    
    public init<PageType: View>(
        pages: [PageType],
        indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic,
        currentPageIndex: Binding<Int>) {
        self.pages = pages.map { AnyView($0) }
        self.indexDisplayMode = indexDisplayMode
        self.currentPageIndex = currentPageIndex
    }
    
    public init<Model, ViewType: View>(
        items: [Model],
        indexDisplayMode: PageTabViewStyle.IndexDisplayMode = .automatic,
        currentPageIndex: Binding<Int>,
        pageBuilder: (Model) -> ViewType) {
        self.pages = items.map { AnyView(pageBuilder($0)) }
        self.indexDisplayMode = indexDisplayMode
        self.currentPageIndex = currentPageIndex
    }
    
    private let pages: [AnyView]
    private let indexDisplayMode: PageTabViewStyle.IndexDisplayMode
    private var currentPageIndex: Binding<Int>
    
    public var body: some View {
        TabView(selection: currentPageIndex) {
            ForEach(Array(pages.enumerated()), id: \.offset) {
                $0.element.tag($0.offset)
            }
        }
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: indexDisplayMode))
    }
}

【讨论】:

  • 'pageBuilder($0).any()' -> 'ViewType' 类型的值没有成员 'any'
  • 对不起,我错过了更换它。我已经调整了答案。 .any() 只是一个自定义视图扩展,可以将任何视图转换为AnyView
  • 是的,我在稍微管理后想通了。相反,我只是在 init 语句中提供页面并丢弃构建器块。感谢更新。这是一个很好的解决方案。
【解决方案5】:

最简单的方法是通过iPages

import SwiftUI
import iPages

struct ContentView: View {
    @State var currentPage = 0
    var body: some View {
        iPages(currentPage: $currentPage) {
            Text("?")
            Color.pink
        }
    }
}

【讨论】:

  • 这是开源的,但不是免费的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 2021-09-23
  • 1970-01-01
  • 2020-09-21
  • 2023-01-11
相关资源
最近更新 更多