返回

弹框多又多,SwiftUI该如何搞?

iOS

使用 SwiftUI 管理多个 Sheet

什么是 Sheet?

在 SwiftUI 中,Sheet 是一种模态视图,它会覆盖当前视图,通常用于显示更多信息或提供交互功能。您可以通过以下代码创建一个 Sheet:

struct ContentView: View {
  @State private var isShowingSheet = false

  var body: some View {
    Button("Show Sheet") {
      isShowingSheet = true
    }
    .sheet(isPresented: $isShowingSheet) {
      Text("This is a sheet")
    }
  }
}

处理多个 Sheet

当您需要显示多个 Sheet 时,可以使用以下方法:

1. 使用多个 State 变量

为每个 Sheet 创建一个 State 变量,并通过这些变量控制它们的显示状态。例如:

struct ContentView: View {
  @State private var isShowingSheet1 = false
  @State private var isShowingSheet2 = false

  var body: some View {
    Button("Show Sheet 1") {
      isShowingSheet1 = true
    }
    .sheet(isPresented: $isShowingSheet1) {
      Text("This is sheet 1")
    }
    Button("Show Sheet 2") {
      isShowingSheet2 = true
    }
    .sheet(isPresented: $isShowingSheet2) {
      Text("This is sheet 2")
    }
  }
}

2. 使用数组

将 Sheet 的 State 变量存储在一个数组中,并通过遍历数组来控制显示状态。例如:

struct ContentView: View {
  @State private var sheetStates = [false, false, false]

  var body: some View {
    ForEach(0..<sheetStates.count) { index in
      Button("Show Sheet \(index + 1)") {
        sheetStates[index] = true
      }
      .sheet(isPresented: $sheetStates[index]) {
        Text("This is sheet \(index + 1)")
      }
    }
  }
}

控制显示顺序

当多个 Sheet 同时出现时,可以使用以下方法控制它们的显示顺序:

1. 使用 ZStack

将 Sheet 放置在一个 ZStack 中,并通过设置它们的 zIndex 属性来控制显示顺序。例如:

struct ContentView: View {
  @State private var isShowingSheet1 = false
  @State private var isShowingSheet2 = false

  var body: some View {
    ZStack {
      if isShowingSheet2 {
        Text("This is sheet 2")
          .zIndex(1)
      }
      if isShowingSheet1 {
        Text("This is sheet 1")
          .zIndex(0)
      }
    }
    Button("Show Sheet 1") {
      isShowingSheet1 = true
    }
    Button("Show Sheet 2") {
      isShowingSheet2 = true
    }
  }
}

2. 使用 presentationMode

通过使用 presentationMode 属性可以控制 Sheet 的显示顺序。例如:

struct ContentView: View {
  @State private var isShowingSheet1 = false
  @State private var isShowingSheet2 = false

  var body: some View {
    Button("Show Sheet 1") {
      isShowingSheet1 = true
    }
    .sheet(isPresented: $isShowingSheet1, onDismiss: {
      isShowingSheet2 = true
    }) {
      Text("This is sheet 1")
    }
    Button("Show Sheet 2") {
      isShowingSheet2 = true
    }
    .sheet(isPresented: $isShowingSheet2) {
      Text("This is sheet 2")
    }
  }
}

结论

通过使用这些技术,您可以轻松地在 SwiftUI 中管理多个 Sheet,并控制它们的显示状态和顺序。这为您提供了在应用程序中创建复杂而交互式界面所需的灵活性。

常见问题解答

  1. 如何关闭 Sheet?
    关闭 Sheet 的最简单方法是设置其 isPresented 属性为 false。

  2. 可以在 Sheet 中使用 SwiftUI 表格视图吗?
    是的,您可以在 Sheet 中使用 SwiftUI 表格视图。

  3. 我可以在 Sheet 中嵌入其他视图吗?
    是的,您可以通过使用 NavigationView 或 Sheet 的 content 属性来嵌套视图。

  4. 我可以动态更改 Sheet 的标题吗?
    是的,您可以通过设置 Sheet 的 title 属性来动态更改标题。

  5. 我可以自定义 Sheet 的外观吗?
    是的,您可以通过设置 Sheet 的 background、foregroundColor 和 presentationDetents 等属性来自定义它的外观。