SwiftUIでPopupViewを作成する
公開日: 2024-02-07 22:46:25
SwiftUIでPopupViewを使って上部の画面外から、スライドして上部に表示されるようなViewのコードがこちらです。
import SwiftUI
struct ContentView: View {
@State private var showPopup = false
var body: some View {
ZStack(alignment: .top) {
VStack {
Spacer()
Button("Show Popup") {
withAnimation {
showPopup = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
withAnimation {
showPopup = false
}
}
}
Spacer()
}
if showPopup {
PopupView()
// 画面の幅の95%を計算して設定
.frame(width: UIScreen.main.bounds.width * 0.95, height: UIScreen.main.bounds.width * 0.325)
.transition(.asymmetric(insertion: .move(edge: .top), removal: .move(edge: .top)))
.zIndex(1)
.cornerRadius(8)
}
}
.edgesIgnoringSafeArea(.top) // セーフエリアの上部を無視する
}
}
struct PopupView: View {
var body: some View {
Text("Popup View")
.frame(maxWidth: .infinity)
.frame(height: UIScreen.main.bounds.width * 0.2)
.background(Color.blue)
.foregroundColor(.white)
}
}
今回注目すべきコードはこちらの部分で、.moveを.topとすると上から、.leadingとすると左から表示させれます。
.removalの値も同様に.topとすると上へ消えていくアニメーションが作れます。
.transition(.asymmetric(insertion: .move(edge: .top), removal: .move(edge: .top)))
