この記事でやること
- Swiftで、背景をスクロール可能なハーフモーダルを実装する

当記事は執筆時点での理解をメモとして残したものです。
間違いがあったら、コメントにて教えていただけると嬉しいです🙏
目次
環境
この記事は以下のバージョン時点での情報をまとめています。
【XCode】16.4
【Swift】6.2
【iOS】18.5
【macOS】Sequoia 15.5
完成イメージ
実装方法
シート表示したい要素に.presentationDetents([.medium, .large])
と.presentationBackgroundInteraction(.enabled)
モディファイアを付与する。
サンプルコード
import SwiftUI
struct ContentView: View {
@State private var showingSheet = false
var body: some View {
ScrollView{
Text("メインビュー")
.font(.largeTitle)
.padding()
Button("シートを表示") {
showingSheet = true
}
.font(.title2)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
ForEach(1...20, id: \.self) { index in
Text("\(index)番目の要素")
.padding()
}
}
.sheet(isPresented: $showingSheet) {
SheetView()
.presentationDetents([.medium, .large]) // ハーフモーダルを表示
.presentationBackgroundInteraction(.enabled) // 背景のスクロールを有効化
}
}
}
#Preview {
ContentView()
}
struct SheetView: View {
@Environment(\.dismiss) private var dismiss
var body: some View {
VStack {
Text("シートビュー")
.font(.largeTitle)
.padding()
Button("閉じる") {
dismiss()
}
.font(.title2)
.padding()
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}
参考
Apple Developer Documentation




presentationDetents(_:) | Apple Developer Documentation
Sets the available detents for the enclosing sheet.
Apple Developer Documentation




presentationBackgroundInteraction(_:) | Apple Developer Documentation
Controls whether people can interact with the view behind a presentation.
コメント