1
1

More than 1 year has passed since last update.

【SwiftUI】非同期処理中にButtonだけを非活性にしてインジケータを出すModifier

Last updated at Posted at 2021-12-06

やりたいこと

Twitterで流れてきたこの記事を読んで
同じことを簡単にiOSのボタンで実現したい

できたもの

参考

やったこと

Modifierを作る

こんな感じで使えるようにModifierを作ります

Button()
  .modifier(...)

この場合contentはこのmodifierをつけるButtonのことです

struct Loadable: ViewModifier {
    @Binding var isLoading: Bool
    var progressColor: Color = .gray

    func body(content: Content) -> some View {
        ZStack {
            if isLoading {
                content.opacity(0.3)
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: progressColor))
            } else {
                content
            }
        }.scaledToFit()
    }
}

Buttonで使う

実際の使い方はこんな感じです。

struct ContentView: View {
    @State private var isLoading: Bool = false

    var body: some View {
        Button(action: {
            isLoading.toggle()
            DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
                isLoading.toggle()
            }
        }) {
            Text("Start")
                .frame(width: 200, height: 40, alignment: .center)
                .background(.orange)
                .foregroundColor(.white)
                .cornerRadius(20)
        }
        .disabled(isLoading)
        .modifier(Loadable(isLoading: $isLoading))
    }
}
1
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
1
1