やりたいこと
Twitterで流れてきたこの記事を読んで
同じことを簡単にiOSのボタンで実現したい
できたもの
記事書きました!
— Yusuke Miyata (@yuskey38) December 6, 2021
【SwiftUI】非同期処理中にButtonだけを非活性にしてインジケータを出すModifier #Qiita https://t.co/OOKqiMQ4eB pic.twitter.com/rzcXiRDOtm
参考
やったこと
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))
}
}