首页 > 解决方案 > 提出警报

问题描述

我使用 Xcode 11 Beat 5 运行 SwiftUI,我希望添加一个警报以在点击按钮时向用户显示。

我有问题。

HStack{
    Text("Inverted V")
      .font(.largeTitle)
      .fontWeight(.bold)
      .foregroundColor(Color.black)
    Spacer()
    Button(action: {

    }, label: {
      Image(systemName: "questionmark.circle.fill")
      .resizable()
      .frame(width: 30, height: 30)
      .foregroundColor(.red)

    }).onTapGesture {
      print("Hello Print")

  }}

有人可以帮助提供所需的代码吗?我是否将它放在 onTapGesture 括号内?

我有一个 @State var 显示Alert = false

先感谢您。

标签: xcodealertswiftui

解决方案


您将使用类似于以下代码的内容。如果您使用的是 onTapGesture,则不需要 Button。

import SwiftUI

struct ContentView: View {
    @State var showingAlert: Bool = false
    var body: some View {
        HStack{
            Text("Inverted V")
                .font(.largeTitle)
                .fontWeight(.bold)
                .foregroundColor(Color.black)
            Spacer()

            Image(systemName: "questionmark.circle.fill")
                .resizable()
                .frame(width: 30, height: 30)
                .foregroundColor(.red)
                .onTapGesture {
                    print("Hello Print")
                    self.showingAlert = true
            }
        }.alert(isPresented: $showingAlert, content: {
            Alert(title: Text("Error"), message: Text("Error Reason"), dismissButton: .default(Text("OK")))
        })
    }
}

推荐阅读