FullscreenPopup

一个可以在 SwiftUI 中 NavigationBar 之上显示弹窗的库

Language:Swift License:MIT Latest Release Twitter

动机

这个库是为了解决在 SwiftUI 中显示自定义提示框时遇到的特定挑战而创建的,尤其是在涉及模态视图时。 在标准实践中,开发者可能会使用 ZStack 或 overlay 修饰符来在现有视图之上分层额外的视图。 然而,这种方法在模态呈现方面显示出其局限性。

当模态视图处于活动状态时,使用 ZStack 或 overlay 分层的任何额外视图都会被限制在模态视图的边界内。 这种限制意味着它们无法扩展到整个屏幕,而这通常是需要自定义提示框来完全吸引用户注意力并防止与底层内容进行任何交互的关键要求。

这个库通过利用 fullscreenCover 修饰符提供了一个解决方案,确保自定义提示框可以呈现在整个屏幕上,而不管是否有任何活动的模态视图。 这种方法确保自定义提示框不受模态视图的边界的限制,使其能够完全覆盖背景内容并防止意外的交互。

ZStack 或 overlay 这个库

用法

以下是如何使用它

import SwiftUI
import FullscreenPopup

public struct ContentView: View {
    @State var isPopupPresented = false
    public var body: some View {
        Button("show popup") {
            isPopupPresented = true
        }
        .popup(isPresented: $isPopupPresented) {
            // Your custom popup content
        }
    }
}

自定义动画

您还可以通过向 .popup 修饰符提供 animation 参数来自定义动画。 这是一个例子

.popup(isPresented: $isPopupPresented, duration: .seconds(0.5), animation: .easeIn(duration: 0.5)) {
    // Your custom popup content
}

警告 duration 参数必须大于 animationduration

自定义背景

您还可以自定义出现在弹窗后面的背景视图。 默认情况下,使用半透明的黑色视图。 要使用不同的视图,请向 .popup 修饰符提供 background 参数

.popup(isPresented: $isExample1Presented) { isPresented in
    LinearGradient(gradient: Gradient(colors: [.blue, .purple]), startPoint: .top, endPoint: .bottom)
        .opacity(isPresented ? 0.5 : 0)
} content: {
    // Your custom popup content
}

基于项目的呈现

使用基于项目的呈现,您可以根据符合 Identifiable 和 Equatable 协议的对象显示弹窗。 当您有一个项目列表,并且想要在选择特定项目时显示该项目的弹窗时,这尤其有用。

以下是如何使用它

public struct ContentView: View {
    @State private var selectedItem: Item? = nil
    public var body: some View {
        List(items) { item in
            Text(item.name)
                .onTapGesture {
                    selectedItem = item
                }
        }
        .popup(item: $selectedItem) { item in
            // Your custom popup content based on the selected item
        }
    }
}

添加延迟

delay 参数允许您指定显示弹窗之前的延迟。 这对于将弹窗显示与其他 UI 动画或操作进行协调非常有用。 以下是如何使用它的示例

.popup(isPresented: $isPopupPresented, delay: .seconds(0.3)) {
    // Your custom popup content
}

在这个例子中,弹窗将在触发事件后延迟 0.3 秒出现。

安装

let package = Package(
    name: "YourProject",
    ...
    dependencies: [
        .package(url: "https://github.com/Ryu0118/swift-fullscreen-popup", exact: "0.1.0")
    ],
    targets: [
        .target(
            name: "YourTarget",
            dependencies: [
                .product(name: "FullscreenPopup", package: "swift-fullscreen-popup"),
            ]
        )
    ]
)