Toastify 是一个轻量级的 SwiftUI 框架,旨在应用程序中显示可自定义的 Toast 消息。它支持持久性 Toast,即使在屏幕之间导航时也保持可见。这个框架可以轻松添加非侵入性的、简短的通知,从而增强用户交互,而不会中断应用程序的流程。
您可以使用 Swift Package Manager 将 Toastify 添加到您的项目中
File > Swift Packages > Add Package Dependency
。https://github.com/vasantp20/Toastify.git
)。要手动将 Toastify 添加到您的项目中
Toastify
文件夹拖到您的 Xcode 项目中。Toastify
在您的目标设置中的 Link Binary with Libraries
部分下列出。您可以使用 showToast
函数显示一个简单的 toast 消息
import Toastify
struct ContentView: View {
var body: some View {
VStack {
Button("Show Toast") {
ToastManager.shared.showToast(message: "Hello, World!")
}
}
}
}
Toastify 现在支持可自定义的 toast 视图,允许开发者传入他们自己的 SwiftUI 视图作为 toast 消息。这项新功能为设计 toast 消息提供了更大的灵活性,使其更容易根据不同的用例调整 Toastify。
要创建自定义 toast 视图,您的视图必须遵循 ToastViewProtocol
协议,这本质上是 SwiftUI 视图的协议。
示例
struct CustomToastView: ToastViewProtocol {
var message: String
var body: some View {
Text(message)
.font(.headline)
.padding()
.background(Color.red.opacity(0.8))
.cornerRadius(12)
.shadow(radius: 10)
}
}
struct ContentView: View {
var body: some View {
VStack {
Button("Show Custom Toast") {
let customToast = CustomToastView(message: "This is a custom toast!")
ToastManager.shared.showToast(toastView: customToast, duration: 3.0)
}
}
}
}
在这个例子中
CustomToastView
定义了一个带有红色背景和圆角的 toast。showToast(toastView:)
方法执行以下操作
即使在导航期间,toast 也会在窗口级别保持持久性。您可以在导航到新屏幕之前显示 toast,消息将保持可见
Button("Navigate and Toast") {
ToastManager.shared.showToast(message: "Navigating!")
// Navigate to the next view
let nextVC = UIHostingController(rootView: NextView())
UIApplication.shared.windows.first?.rootViewController?.present(nextVC, animated: true)
}
我们欢迎对 Toastify 的贡献!欢迎随时提交 pull request、报告问题或建议新功能。在贡献之前,请查看贡献指南。
Toastify 在 MIT 许可证下获得许可。有关详细信息,请参阅 LICENSE 文件。