SwiftUI

SwiftUI实战-UIPageViewController 轮

2022-06-16  本文已影响0人  ISwiftUI

SwiftUI实战系列

本章内容

UIPageViewController 实现轮播图
1、支持无限轮播
2、解决UIPageViewController导致导航栏无法隐藏的问题
3、支持拖动暂停定时器,放开继续定时轮播

效果图:


UIPageViewController 实现轮播图.gif

相关源码:
ContentView.swift

import SwiftUI

struct ContentView: View {
    
    @State var currentPage: Int = 0
    
    var body: some View {
        NavigationView {
            VStack {
                //轮播图
                SwiperView(items: ["banner1", "banner2", "banner3", "banner4"].map { string in
                    NavigationLink(destination: Text(string), label: {
                        Image(string).resizable()
                    })
                    .buttonStyle(OriginalButtonStyle())
                    
                }, currentPage: $currentPage)
                .aspectRatio(7/3, contentMode: .fit)
                .cornerRadius(12)
                .padding(.horizontal)
                
                Spacer()
            }
            //.navigationBarHidden(true)
            .navigationTitle("轮播图")
            .navigationBarTitleDisplayMode(.inline)
        }
        .navigationViewStyle(StackNavigationViewStyle())
    }
}

struct OriginalButtonStyle : ButtonStyle{
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
    }
}

SwiperControl.swift

import SwiftUI

struct SwiperControl: UIViewRepresentable {

    var numOfPages:Int
    @Binding var currentPage:Int
    
    func makeUIView(context: Context) -> UIPageControl {
        let control = UIPageControl()
        control.currentPage = 0
        control.numberOfPages = numOfPages
        control.addTarget(context.coordinator, action: #selector(context.coordinator.onChanged(sender:)), for: .valueChanged)
        return control
    }
    
    func updateUIView(_ uiView: UIPageControl, context: Context) {
        uiView.currentPage = currentPage
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    class Coordinator: NSObject {
        var parent:SwiperControl
        
        init(_ parent: SwiperControl) {
            self.parent = parent
        }
        
        @objc func onChanged(sender: UIPageControl){
            parent.currentPage = sender.currentPage
        }
    }
    
}

SwiperView.swift

上一篇下一篇

猜你喜欢

热点阅读