Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show partial previous and next item on PageTabViewStyle (SwiftUI 2.0) or PageViewController/PageView (with UIKit interface)

I am working with SwiftUI 2.0 and actually, I am happy that Apple introduced PageTabViewStyle to simply create a pager. But unfortunately, I am not able to implement it in a way I would like to. Is it possible to create a pager (PageTabViewStyle) that shows a little piece of the previous and next item?

Picture 1: Desired behavior

Desired behavior

I tried it with the new PageTabViewStyle and some combinations of paddings and/or offsets and I also tried to interface with UIKit (PageView / PageViewController / PAgeViewControl). But same behavior here, I only see the selected item, even if it doesn’t cover the entire width.

Picture 2: Current behavior

Current behavior

SwiftUI 2.0 - PageTabViewStyle integration

The following code snipped is a very simple implementation of the PageTabViewStyle, but if you have ideas, you can show me on this example what I can do to make it work:

import SwiftUI

struct ContentView: View {

    let colors: [Color] = [.red, .green, .yellow, .blue]
    
    var body: some View {
        
        TabView {
            ForEach(0..<6) { index in
                HStack() {
                    Text("Tab \(index)")
                        .font(.title)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .background(colors[index % colors.count])
                        .cornerRadius(8)
                }
                .frame(width: 300, height: 200)
            }
        }.tabViewStyle(PageTabViewStyle())
    }
}

UIKit interfacing

The following code is from the example by Apple, maybe you can show me here how to get the desired behavior:

PageViewController

/*
See LICENSE folder for this sample’s licensing information.

Abstract:
A view that wraps a UIPageViewController.
*/

import SwiftUI
import UIKit

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,
            options: [UIPageViewController.OptionsKey.interPageSpacing: 5]
        )
        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
            }
        }
    }
}

PageView

/*
See LICENSE folder for this sample’s licensing information.

Abstract:
A view for bridging a UIPageViewController.
*/

import SwiftUI

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: .bottomTrailing) {
            PageViewController(controllers: viewControllers, currentPage: $currentPage)
            PageControl(numberOfPages: viewControllers.count, currentPage: $currentPage)
                .padding(.trailing)
                
        }
    }
}

Thanks, Sebastian

like image 963
Sebastian Fox Avatar asked Jul 25 '20 23:07

Sebastian Fox


1 Answers

I did not find anything out-of-the-box, so I implemented it like this in SwiftUI:

Carousel:

import Foundation
import SwiftUI

struct Carousel<Content: View,T: Identifiable>: View {
    var content: (T) -> Content
    var list: [T]
    
    var spacing: CGFloat
    var trailingSpace: CGFloat
    @Binding var index: Int
    
    
    init(spacing: CGFloat = 15,trailingSpace: CGFloat = 200,index: Binding<Int>,items: [T],@ViewBuilder content: @escaping (T)->Content){
        
        self.list = items
        self.spacing = spacing
        self.trailingSpace = trailingSpace
        self._index = index
        self.content = content
    }
    
    @GestureState var offset: CGFloat = 0
    @State var currentIndex: Int = 0
    
    var body: some View{
        
        GeometryReader{proxy in
            
            let width = proxy.size.width - (trailingSpace - spacing)
            let adjustMentWidth = (trailingSpace / 2) - spacing
            
            HStack(spacing: spacing){
                ForEach(list){item in
                    content(item)
                        .frame(width: proxy.size.width - trailingSpace, height: 100)
                }
            }
            .padding(.horizontal,spacing)
            .offset(x: (CGFloat(currentIndex) * -width) + (currentIndex != 0 ? adjustMentWidth : 0) + offset)
            .gesture(
                DragGesture()
                    .updating($offset, body: { value, out, _ in
                        out = value.translation.width
                    })
                    .onEnded({ value in
                        
                        let offsetX = value.translation.width
                        let progress = -offsetX / width
                        let roundIndex = progress.rounded()
                        currentIndex = max(min(currentIndex + Int(roundIndex), list.count - 1), 0)
                        currentIndex = index
                    })
                    .onChanged({ value in
                        let offsetX = value.translation.width
                        let progress = -offsetX / width
                        let roundIndex = progress.rounded()
                        index = max(min(currentIndex + Int(roundIndex), list.count - 1), 0)
                    })
            )
        }
        .animation(.easeInOut, value: offset == 0)
    }
}

User (simplified):

import Foundation
import SwiftUI

struct User: Identifiable{
    var id = UUID().uuidString
    var userName: String
    var userImage: String
}

ContentView:

import SwiftUI

struct ContentView: View {
    
    @State var currentIndex: Int = 0
    @State var users: [User] = []
    
    var body: some View {
        VStack() {
            Carousel(index: $currentIndex, items: users) {user in
                
                GeometryReader{proxy in
                    
                    let size = proxy.size
                    
                    Image(user.userImage)
                        .resizable()
                        .aspectRatio(contentMode: .fill)
                        .frame(width: size.width)
                        .cornerRadius(12)
                }
            }
            .padding(.vertical,40)
            
            // Indicator dots
            HStack(spacing: 10){
                
                ForEach(users.indices,id: \.self){index in
                    
                    Circle()
                        .fill(Color.black.opacity(currentIndex == index ? 1 : 0.1))
                        .frame(width: 10, height: 10)
                        .scaleEffect(currentIndex == index ? 1.4 : 1)
                        .animation(.spring(), value: currentIndex == index)
                }
            }
            .padding(.bottom,40)
        }
        .onAppear {
            for index in 1...5{
                users.append(User(userName: "User\(index)", userImage: "user\(index)"))
            }
        }
    }
}
like image 102
Sebastian Fox Avatar answered Nov 15 '22 05:11

Sebastian Fox