美文网首页SwiftUI
SwiftUI简单的PageControl

SwiftUI简单的PageControl

作者: zjam9333 | 来源:发表于2022-01-25 14:20 被阅读0次

自制一个PageControl:要求当前页面对应的“点”逐渐变长、逐渐变色

ezgif-5-2b04891f9f.gif

//  PageControl.swift
//  SL_SwiftUI
//
//  Created by zjj on 2022/1/25.
//

import SwiftUI

struct PageControl: View {
    let currentPage: CGFloat
    let pageCount: Int
    let tintColor: Color
    let normalColor: Color

    var body: some View {
        HStack(alignment: .center, spacing: 6) {
            ForEach(0 ..< pageCount) { index in
                let floatIndex = CGFloat(index)
                let percent = 1 - (abs(floatIndex - currentPage) / 1)
                let fixedPercent = percent < 0 ? 0 : percent
                let width: CGFloat = abs(6 * fixedPercent) + 4
                ZStack {
                    normalColor
                    tintColor.opacity(fixedPercent)
                }
                .cornerRadius(2)
                .frame(width: width, height: 4)
            }
        }
    }
}

使用传入页数和当前页面即可:

PageControl(currentPage: currentPage,
        pageCount: DataType.allCases.count,
        tintColor: Color(.systemBlue),
        normalColor: Color(.lightGray))
.frame(height: 20)

相关文章

网友评论

    本文标题:SwiftUI简单的PageControl

    本文链接:https://www.haomeiwen.com/subject/msuwhrtx.html