メインコンテンツへスキップ

機能はTaskのsleepが実際に役立つコードを書いたので、今日はTaskのsleepについて深堀りしてみるよ

    //
    //  ContentView.swift
    //  SwiftUIShape
    //
    //  Created by tsu-na-gu on 2026/04/10.
    //
    
    import SwiftUI
    
    struct ContentView: View {
        private var purpleGradient = LinearGradient(gradient: Gradient(colors: [Color(red: 207/255, green: 150/255, blue: 207/255), Color(red: 107/255, green: 116/255, blue: 179/255)]), startPoint: .trailing, endPoint: .leading)
        @State private var progress = 0.0
        var body: some View {
            VStack {
                ZStack {
                    Circle()
                        .stroke(Color(.systemGray6), lineWidth: 20)
                        .frame(width: 300, height: 300)
                    
                    Circle()
                        .trim(from:0.0, to: progress)
                        .stroke(purpleGradient, lineWidth: 20)
                        .frame(width: 300, height: 300)
                        .rotationEffect(.degrees(-90))
                        .overlay {
                            VStack {
                                Text("\(Int(progress * 100))%")
                                    .font(.system(size: 80, weight: .bold, design: .rounded))
                                    .foregroundColor(.gray)
                                Text("Complete")
                                    .font(.system(.body, design: .rounded))
                                    .bold()
                                    .foregroundColor(.gray)
                            }
                        }
                    
                }
                .padding(100)
                Button {
                    Task {
                        await progressStart()
                    }
                } label: {
                    Label("Start", systemImage: "play.circle")
                        .foregroundStyle(.white)
                }
                .buttonStyle(.borderedProminent)
            }
        }
        private func progressStart() async {
            progress = 0.0
            
            for i in 0...100 {
                try? await Task.sleep(for: .milliseconds(80))
                withAnimation(.linear(duration: 0.08)) {
                    progress = Double(i) / 100.0
                }
            }
        }
    }
    
    
        
    
    #Preview {
        ContentView()
    }
     
     
    精神障害手帳2級の47歳で無職です。広汎性発達障害と診断されていますが、ADHD傾向が強いと自分では思っています。生きる目的を見失って居た頃にHoudiniと出会い、唯一の生きる希望がこのソフトを学ぶことになりました。白黒思考があり、鬱になると死ぬことばかり考えています。

    あなたへのおすすめ