【问题标题】:SwiftUI - show Alert from Button inside of ToolbarItemSwiftUI - 从 ToolbarItem 内的按钮显示警报
【发布时间】:2021-04-02 15:24:44
【问题描述】:

我想做一些类似于下面的代码,当用户点击导航栏项目按钮时它会显示一个警报。但是下面的代码不起作用,警报不显示。

我无法将警报修饰符添加到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"))
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 最简单的解决方案是将每个按钮变成自己的子视图。这样每个子视图都可以有自己的 .alert 修饰符。
  • 这也可能有效,但对于这个例子,我认为使用@Asperi 的解决方案更容易

标签: ios swiftui swiftui-alert


【解决方案1】:

解决方案是在工具栏之外使用警报并使用不同的构造函数。使用 Xcode 12.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))
            }
        }
    }
}

【讨论】:

  • 这可行,但你需要确保你使 String 符合 Identifiable
猜你喜欢
  • 1970-01-01
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多