我想做一些类似于下面代码的事情,当用户点击导航栏项目按钮时,它会显示一个警告。但是,下面的代码不起作用,警报也不会显示。
我无法将警报修饰符添加到NavigationView中,因为我的实际应用程序更复杂,并且VStack是另一个文件中的视图,而且向同一视图添加多个警报修饰符也不起作用(只有最后添加的一个有效)。
import SwiftUI
struct SOQuestionView: View {
@State private var showAlert1 = false
@State private var showAlert2 = false
var body: some View {
NavigationView {
VStack {
Text("Click button in toolbar")
}
.navigationBarTitle(Text("Title"))
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
showAlert1 = true
}) {
Image(systemName: "square.and.arrow.up")
}
.alert(isPresented: $showAlert1) {
Alert(title: Text("Alert 1"))
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
showAlert2 = true
}) {
Image(systemName: "square.and.arrow.up.fill")
}
.alert(isPresented: $showAlert2) {
Alert(title: Text("Alert 2"))
}
}
}
}
}
}

发布于 2020-12-24 12:42:14
解决方案是在工具栏之外使用alert,并使用不同的构造函数。使用Xcode12.1/ iOS 14.1进行测试。

struct SOQuestionView: View {
@State private var alertItem: String?
var body: some View {
NavigationView {
VStack {
Text("Click button in toolbar")
}
.navigationBarTitle(Text("Title"))
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: {
alertItem = "Alert 1"
}) {
Image(systemName: "square.and.arrow.up")
}
}
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: {
alertItem = "Alert 2"
}) {
Image(systemName: "square.and.arrow.up.fill")
}
}
}
.alert(item: $alertItem) { item in
Alert(title: Text(item))
}
}
}
}https://stackoverflow.com/questions/65433858
复制相似问题