どうも、ちょげ(@chogetarou)です。
Alertを特定の時間経過後に自動で閉じる方法を紹介します。
方法

Alertを自動で閉じるには、DispatchQueueを使います。
まず、「DispatchQueue.main.asyncAfter」を呼び出します。
次に、asyncAfterの引数「deadline」に閉じる時間を指定し、asyncAfterにクロージャを追加します。
DispatchQueue.main.asyncAfter(deadline: .now() + time) {}
あとは、asyncAfterのクロージャーに、表示・非表示に使っている変数の値を「false」もしくは非表示の値に指定します。
DispatchQueue.main.asyncAfter(deadline: closeTime) {
showAlert = false //変数の値をアラートが閉じる値に
}
使用例
struct ContentView: View {
@State var showAlert = false;
var body: some View {
VStack {
Button(action: {
showAlert = true;
//3秒後に閉じる
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.showAlert = false;
}
}){
Text("Show")
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Title"),
message: Text("This is message."),
primaryButton: .default(Text("OK")){
print("Okで閉じる")
},
secondaryButton: .cancel(Text("Cancel")){
print("Cancelで閉じる")
}
)
}
}
}
}
コメント