Alert作为音讯提示的一种方式也是非常方便有用的。当然它的运用方式也很简单。咱们一起来看看。
单个按钮的Alert
只有一个承认按钮和标题,当咱们点击Alert Button时会弹出如下款式的alert
struct AlertSample: View {
@State private var showAlert: Bool = false
@State private var backgronudColor: Color = .white
var body: some View {
ZStack {
backgronudColor
.edgesIgnoringSafeArea(.all)
VStack {
Button("Alert Button") {
showAlert.toggle()
}
.foregroundColor(Color.black)
}
.alert("Message", isPresented: $showAlert) {
Button(role: .cancel) {} label: {
Text("Cancel")
}
}
}
}
}
单个按钮带有子音讯的Alert
只需把上述代码改成一下代码就能够完成有子音讯的alert,作用如下
struct AlertSample: View {
@State private var showAlert: Bool = false
@State private var backgronudColor: Color = .white
var body: some View {
ZStack {
backgronudColor
.edgesIgnoringSafeArea(.all)
VStack {
Button("Alert Button") {
showAlert.toggle()
}
.foregroundColor(Color.black)
}
.alert("Message", isPresented: $showAlert) {
Button(role: .cancel) {} label: {
Text("Cancel")
}
} message: {
Text("This is Swftui sample")
}
}
}
}
双按钮的Alert
.alert("Message", isPresented: $showAlert) {
Button(role: .cancel) {} label: {
Text("Cancel")
}
Button(role: .destructive) {
backgronudColor = .red
} label: {
Text("Delete")
}
} message: {
Text("This is Swftui sample")
}
alert办法的界说中,actions能够有多个值。办法界说如下:
public func alert<A, M>(_ titleKey: LocalizedStringKey,
isPresented: Binding<Bool>,
@ViewBuilder actions: () -> A,
@ViewBuilder message: () -> M
) -> some View where A : View, M : View
以上代码作用如下:
运用传递值来显现音讯
这个是什么意思呢?咱们先来看看办法界说
public func alert<A, M, T>(_ titleKey: LocalizedStringKey,
isPresented: Binding<Bool>,
presenting data: T?,
@ViewBuilder actions: (T) -> A,
@ViewBuilder message: (T) -> M
) -> some View where A : View, M : View
其间presenting便是咱们需要用来显现在message中的值,尤其当你需要动态删除某些数据之前,对特定数据做提示时就需要用到这个办法。
struct AlertSample: View {
@State private var showAlert: Bool = false
@State private var backgronudColor: Color = .white
@State var name: String = ""
var body: some View {
ZStack {
backgronudColor
.edgesIgnoringSafeArea(.all)
VStack {
Button("Alert Button") {
name = "狂徒东北吴彦祖"
showAlert.toggle()
}
.foregroundColor(Color.black)
}
.alert(
"Message",
isPresented: $showAlert,
presenting: name
) { str in
Button(role: .cancel) {} label: {
Text("撤销")
}
Button(role: .destructive) {
backgronudColor = .red
} label: {
Text("拉黑")
}
} message: { str in
Text("你去确定要拉黑(name)吗?")
}
}
}
}
作用如下:
以上便是alert的根本运用。
我们有什么观点呢?欢迎留言评论。
大众号:RobotPBQ