Skip to content

允许自定义颜色和尺寸

当然可以!让我们一起探索如何让你的自定义加载指示器拥有更强的适应性,通过自定义颜色和尺寸来满足各种设计需求。🎨✨

自定义颜色的力量

颜色是用户界面设计中非常重要的一环。通过允许自定义颜色,你可以确保加载指示器与你的应用主题完美融合。🌈

  • 使用 Color 类型属性来控制指示器的颜色。
  • 提供一个初始化器参数,允许开发者传入他们想要的颜色。
  • 利用 SwiftUI 的 .foregroundColor() 修饰符来应用颜色。

例如:

swift
struct CustomProgressIndicator: View {
    let color: Color
    let size: CGFloat

    var body: some View {
        Circle()
            .trim(from: 0.0, to: 0.8)
            .stroke(color, style: StrokeStyle(lineWidth: size * 0.1, lineCap: .round))
            .frame(width: size, height: size)
            .rotationEffect(.degrees(rotation))
    }
}

尺寸的灵活调整

尺寸的自定义同样重要。不同的屏幕尺寸和布局可能需要不同大小的加载指示器。📏

  • 使用 CGFloat 类型的属性来控制指示器的大小。
  • 确保你的视图能够根据传入的尺寸进行缩放。
  • 考虑使用 GeometryReader 来动态调整尺寸,以适应不同的屏幕。

例如:

swift
struct CustomProgressIndicator: View {
    let color: Color
    let size: CGFloat

    var body: some View {
        Circle()
            .trim(from: 0.0, to: 0.8)
            .stroke(color, style: StrokeStyle(lineWidth: size * 0.1, lineCap: .round))
            .frame(width: size, height: size)
            .rotationEffect(.degrees(rotation))
    }
}

代码示例与实践

让我们通过一个完整的例子来展示如何实现颜色和尺寸的自定义。🚀

  1. 定义一个 CustomProgressIndicator 结构体,包含 colorsize 属性。
  2. body 中使用这些属性来设置加载指示器的颜色和大小。
  3. 提供一个初始化器,允许用户传入自定义的颜色和尺寸。
swift
struct CustomProgressIndicator: View {
    let color: Color
    let size: CGFloat
    @State private var rotation: Double = 0

    init(color: Color = .blue, size: CGFloat = 50) {
        self.color = color
        self.size = size
    }

    var body: some View {
        Circle()
            .trim(from: 0.0, to: 0.8)
            .stroke(color, style: StrokeStyle(lineWidth: size * 0.1, lineCap: .round))
            .frame(width: size, height: size)
            .rotationEffect(.degrees(rotation))
            .onAppear {
                withAnimation(Animation.linear(duration: 1).repeatForever(autoreverses: false)) {
                    rotation = 360
                }
            }
    }
}

通过以上步骤,你就可以创建一个高度可定制的加载指示器,让你的应用更加出色!🎉

本站使用 VitePress 制作