SwiftUI Sheet 与 fullScreenCover 合集

fullScreenCover

参考:How to present a full screen modal view using fullScreenCover()

与 sheet 一致。

Custom Sheet

参考:

1
2
3
4
5
6
7
8
9
.presentationBackground(.thinMaterial)			// 模糊效果
.presentationBackground(.yellow) // 设置颜色
.presentationCornerRadius(8) // 圆角
// When it first appears, the bottom sheet is displayed in medium size. You can expand it to large size by dragging the sheet.
.presentationDetents([.medium, .large])
// supports 4 different sizes including: around 10% of the screen height;a fixed height of 200 points;the standard Medium and Large sizes
.presentationDetents([.fraction(0.1), .height(200), .medium, .large])
.presentationDragIndicator(.hidden) // 隐藏指示器
.presentationDragIndicator(.visible)

dismiss()

在 sheet 和 fullScreenCover 中都可以使用

1
2
3
4
5
6
@Environment(\.presentationMode) var presentationMode
// Use: presentationMode.wrappedValue.dismiss()
// 该方法在 iOS 15.0 后被 dismiss() 替代

@Environment(\.dismiss) var dismiss
// Use: dismiss()

.popover

目前看下来 .popover.sheet 没什么区别

1
2
3
4
5
6
7
8
9
10
11
12
13
struct ContentView: View {
@State private var showingPopover = false
var body: some View {
Button("Show Menu") {
showingPopover = true
}
.popover(isPresented: $showingPopover) {
Text("Your content here")
.font(.headline)
.padding()
}
}
}

报错提示 Attempt to present … on … while a presentation is in progress.

参考:

  1. How to Fix SwiftUI Sheet Dismissing on First Launch
  2. SwiftUI Presentation / Attempt to present View on … which is already presenting

Your .sheet(isPresented: $showingOtherView) { is inside the ForEach. When you set showingOtherView to true, all the sheets in the ForEach will try to present. That’s a looooot of sheets.

传入 sheet 的参数赋值无效

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct ContentView: View {

@State private var item: Item?
@State private var isPresented: Bool = false

var body: some View {
Button("Sheet Button") {
let newItem = Item(text: "Hello World")
item = newItem
isPresented.toggle()
}
.sheet(isPresented: $isPresented) {
if item != nil {
Text(item!.text)
} else {
Text("item is nil")
}
}
}
}

struct Item: Identifiable {
let id: UUID = UUID()
let text: String
}

上述在弹出 sheet 后,显示的内容为「item is nil」。原因是:

The issue is due to sheet is created before button clicked. The solution for your scenario is to use .sheet(item: approach.

参考:Why does state reset to nil after assignment

解决方案:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct ContentView: View {

@State private var item: Item?

var body: some View {
Button("Sheet Button") {
let newItem = Item(text: "Hello World")
item = newItem
}
.sheet(item: $item) { item in
Text(item.text)
}
}
}

struct Item: Identifiable {
let id: UUID = UUID()
let text: String
}

这个用法一般用在 selectedItem 上。


SwiftUI Sheet 与 fullScreenCover 合集
https://wonderhoi.com/2024/10/23/SwiftUI-Sheet-与-fullScreenCover-合集/
作者
wonderhoi
发布于
2024年10月23日
许可协议