一、 背景
最近闲暇时间琢磨了一下Apple生态内的开发。今天需要实现一个简易且快速的Alert弹窗,参考了一些现存的技术文档发现都较为复杂。在快速翻阅了Apple官方的开发文档后,简单整理并记录一个快速实现的方法。
二、 官方文档
苹果官方文档在Modal Presentations部分给出了若干种Alert样式的弹窗方法。需要注意的是之前特别简单粗暴的Alert Structure已经被弃用,在最新版的开发者文档中,Apple给出了一个更灵活也更正式的基于View modifier的Alert弹窗实现方式:
func alert<A, M>(
_ title: Text,
isPresented: Binding<Bool>,
@ViewBuilder actions: () -> A,
@ViewBuilder message: () -> M
) -> some View where A : View, M : View
可以看到标题和触发方式和之前区别不大,都是绑定了一个监控值来在满足条件的时候触发Alert弹窗。但Actions和Message变成了ViewBuilder构造的方式进行传参及显示。这样我们写起来会更加复杂,但同时也更规范,可读性更高,特别是涉及到Alert内容由外部方法执行结果而动态传入不同的信息时显得尤为有用。
三、 一种实现方式
由于我的需求非常简单,Alert弹窗内容几乎都是静态的,经过查阅最新版文档(见此处:alert(_:isPresented:actions:message:) | Apple Developer Documentation),有一种非常接近之前Alert的实现方式:
struct SettingsView: View {
@State private var doAlert = false
let alertTitle: String = "Some Alert Title..."
var body: some View {
HStack{
Text("Some UI Stack")
}.padding(.all)
Button("Apply"){
if someCondition {
doAlert = true
}
}.buttonStyle(.bordered)
.alert(
alertTitle,
isPresented: $doAlert
) {
Button(role: .destructive) {
someBusinessLogic()
} label: {
Text("Some button 1")
}
Button("Some button 2") {
// Some other business logic
}
} message: {
Text("Some detailed message")
}
}
}