Balbas Code

SwiftUIでPopupViewを作成する2

公開日: 2024-02-12 02:02:34
更新日: 2024-02-12 21:44:30

SwiftUIでPopupViewを作成するの第二弾の記事を書きました。


前回の続きで、
・画面上部に表示するPopupView
・画面中央に表示されるPopupView
の2つを同時に表示するようなコードを書きました。


 


ContentView (ボタンとViewを呼ぶ設定)


import SwiftUI

struct ContentView: View {
@State private var showPopup = false
@State private var showPopup2 = false

var body: some View {
GeometryReader { geometry in
ZStack {
// メインのUI(ボタンなど)
VStack {
// PopupViewを表示するボタン 時間で閉じる
Button("Show Popup") {
withAnimation(.easeInOut(duration: 1.0)) {
showPopup = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation(.easeInOut(duration: 1.0)) {
showPopup = false
}
}
}

// PopupView2を表示するボタン ボタンを押したら閉じる
Button("Show Popup 2") {
withAnimation {
showPopup2 = true
}
}
}

// PopupView2の表示制御
if showPopup2 {
PopupView2(closeAction: {
withAnimation {
showPopup2 = false
}
})
.frame(width: UIScreen.main.bounds.width * 0.8, height: UIScreen.main.bounds.width * 0.4)
.transition(.scale)
.zIndex(2)
.cornerRadius(10)
.background(Color.white)
}
}
.frame(width: geometry.size.width, height: geometry.size.height)
.position(x: geometry.size.width / 2, y: geometry.size.height / 2)

// PopupViewの表示制御 画面外におく必要があったのでこちらはZstackとは別に配置
if showPopup {
PopupView()
.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)))//表示と削除方法
.animation(.easeInOut(duration: 1.0), value: showPopup)//アニメーションの設定
.zIndex(3)// 数字が大きほど全面表示
.cornerRadius(8)// 角を削る
// PopupViewの開始位置を画面の上部に設定し、表示・非表示時には画面外に移動
.position(x: geometry.size.width / 2, y: showPopup ? geometry.size.height * 0.16 : -geometry.size.height)
}
}
.edgesIgnoringSafeArea(.all) // セーフエリアを無視
}
}

 


画面上部に表示されるPopupView


// 画面外の上部から表示されるView
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)
}
}

 


画面中央に表示されるPopupView


// 画面の中央に表示されるView
struct PopupView2: View {
var closeAction: () -> Void

var body: some View {
VStack {
Text("Popup View 2")
.foregroundColor(.white)

Button("Close", action: closeAction)
.foregroundColor(.white)
.padding()
.background(Color.red)
.cornerRadius(10)
}
.frame(width: 300, height: 200) // VStack全体のサイズを指定
.background(Color.green) // VStackの背景色
.border(Color.gray, width: 2) // VStackに枠線をつける
}
}

startPopupView1