如何在SwiftUI中实现PageView?

时间:2019-10-15 05:57:10

标签: ios swift swiftui

我是SwiftUI的新手。我有三个视图,希望在PageView中使用它们。我想像滑动浏览器一样滑动每个“视图”,并希望这些小点表示我所在的视图。

5 个答案:

答案 0 :(得分:28)

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

struct PageView<SelectionValue, Content>: View where SelectionValue: Hashable, Content: View {
    @State private var selectionInternal: SelectionValue
    @Binding private var selectionExternal: 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._selectionInternal = .init(initialValue: selection.wrappedValue)
        self._selectionExternal = selection
        self.indexDisplayMode = indexDisplayMode
        self.indexBackgroundDisplayMode = indexBackgroundDisplayMode
        self.content = content
    }

    var body: some View {
        TabView(selection: $selectionInternal) {
            content()
        }
        .onChange(of: selectionInternal) {
            selectionExternal = $0
        }
        .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._selectionInternal = .init(initialValue: 0)
        self._selectionExternal = .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)
                }
            }
        }
    }
}

答案 1 :(得分:4)

页面控制

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

    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) {
        pageViewController.setViewControllers(
            [controllers[currentPage]], direction: .forward, animated: true)
    }

    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)

答案 2 :(得分:1)

对于面向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 { $0.any() }
        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 { pageBuilder($0).any() }
        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))
    }
}

答案 3 :(得分:1)

最简单的方法是通过iPages

import SwiftUI
import iPages

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

答案 4 :(得分:1)

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))
            ]
        )
    }
}