3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SwiftUI】かっこいいゲージを自作する

Posted at

はじめに

iOSの標準のゲージでもいいですが、もっとカッコイイデザインのゲージを使いたいので自作してみます。

実装

import SwiftUI

struct CustomGaugeView: View {
    @Binding var value: CGFloat

    private let maxValue: CGFloat

    init(_ value: Binding<CGFloat>, maxValue: CGFloat) {
        self._value = value
        self.maxValue = maxValue
    }

    var body: some View {
        GeometryReader { proxy in
            levelGauge(proxy: proxy)
        }
    }

    private func levelGauge(proxy: GeometryProxy) -> some View {
        ZStack(alignment: .center) {
            Capsule()
                .foregroundColor(.secondary)

            Capsule()
                .fill(LinearGradient(gradient: .init(colors: [.yellow, .orange]), startPoint: .leading, endPoint: .trailing))
                .frame(width: proxy.size.width * (CGFloat(value) / CGFloat(maxValue)))
                .contentShape(Capsule())
                .frame(maxWidth: .infinity, alignment: .leading)
        }
    }
}

使い方

import SwiftUI

struct ContentView: View {
    @State private var value: CGFloat = 0
    
    private var maxValue: CGFloat = 100
    
    var body: some View {
        VStack(spacing: 50) {
            CustomGaugeView($value, maxValue: maxValue)
                .frame(height: 23)
            
            Slider(value: $value, in: 0...maxValue)
        }
        .padding(.horizontal, 20)
    }
}

注意
frameheightを指定してください

動画

Simulator Screen Recording - iPhone 14 - 2023-06-05 at 22.31.24.gif

おわり

いい感じに作ることができました

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?