SwiftUI:iOS14及以下版本如何实现Alert多选项?
iOS 14及以下SwiftUI实现多选项Alert的原生方案
在iOS 14及以下版本的SwiftUI中,原生Alert组件仅支持最多两个操作按钮(通过primaryButton和secondaryButton参数定义),无法直接使用iOS 15引入的action参数添加多个选项。但可以通过封装苹果原生UIKit框架的UIAlertController来实现多选项功能,这属于原生技术栈内的解决方案。
实现示例代码
首先创建一个基于UIViewControllerRepresentable的封装组件:
import SwiftUI struct MultiOptionAlert: UIViewControllerRepresentable { let title: String let options: [String] let selectionHandler: (String) -> Void let onDismiss: (() -> Void)? func makeUIViewController(context: Context) -> UIAlertController { let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert) // 添加所有选项按钮 for option in options { let action = UIAlertAction(title: option, style: .default) { _ in selectionHandler(option) onDismiss?() } alert.addAction(action) } // 添加取消按钮 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in onDismiss?() } alert.addAction(cancelAction) return alert } func updateUIViewController(_ uiViewController: UIAlertController, context: Context) {} } // 扩展View,简化调用方式 extension View { func multiOptionAlert(isPresented: Binding<Bool>, title: String, options: [String], selectionHandler: @escaping (String) -> Void) -> some View { self.background( EmptyView() .sheet(isPresented: isPresented) { MultiOptionAlert(title: title, options: options, selectionHandler: selectionHandler, onDismiss: { isPresented.wrappedValue = false }) } ) } }
使用方式
在你的SwiftUI视图中直接调用封装好的方法:
struct ContentView: View { @State private var showAlert = false @State private var selectedPackage = "" var body: some View { VStack(spacing: 20) { Button("Show Package Selector") { showAlert = true } Text("Selected Package: \(selectedPackage)") } .multiOptionAlert(isPresented: $showAlert, title: "Choose a package", options: ["Standard", "Pro", "Premium"]) { option in selectedPackage = option } } }
该方案完全基于苹果原生技术实现,未依赖任何第三方库,可满足iOS 14及以下版本的多选项Alert需求。
内容的提问来源于stack exchange,提问作者Nikhil Raj
相关产品推荐
相关产品推荐

