【问题标题】:How to present an Alert in SwiftUI with no buttons如何在没有按钮的 SwiftUI 中显示警报
【发布时间】:2020-06-30 15:13:19
【问题描述】:

我有一种情况,我想通过在用户无法交互的长时间运行操作期间显示 Alert 来重新创建以前的 UIKit 逻辑。

以前在 UIKit 中,它会很简单:

import UIKit

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let alertController = UIAlertController(title: "Loading",
                                                message: nil,
                                                preferredStyle: .alert)
        present(alertController, animated: true, completion: nil)
    }
}

它看起来像这样:

一个简单的基于SwiftUI 的版本可以这样创建:

import SwiftUI

struct ContentView: View {
    @State private var isLoading = true
    
    var body: some View {
        Text("Hello")
            .modifier(LoadingAlert(isPresented: $isLoading))
    }
}

struct LoadingAlert: ViewModifier {
    @Binding var isPresented: Bool

    func body(content: Content) -> some View {
        content
            .alert(isPresented: $isPresented) {
                Alert(title: Text(NSLocalizedString("Loading", comment: "")),
                      dismissButton: .none)
            }
    }
}

无论我使用nil.none 作为dismissButton 参数,还是完全省略该行,它都将使用默认的OK 按钮,并生成:

我确实修改了Alert 参数,发送了一个带有空title 的按钮,但结果是这样,它不像我想要的那样干净:

dismissButton: .default(Text("")))

根据我所见,根据检查其初始化程序,SwiftUI 中的警报似乎不支持我想要的。

/// Creates an alert with one button.
public init(title: Text, message: Text? = nil, dismissButton: Alert.Button? = nil)

/// Creates an alert with two buttons.
///
/// - Note: the system determines the visual ordering of the buttons.
public init(title: Text, message: Text? = nil, primaryButton: Alert.Button, secondaryButton: Alert.Button)

对于这个项目,目标是充分利用 SwiftUI,但似乎这是我们无法获得预期结果的场景。

我的看法是要么我们必须引入基于 UIKit 的 AlertController,要么使用不同的效果来指示状态。但是,我很想在这里犯错。

【问题讨论】:

    标签: ios swiftui ios13 swiftui-alert


    【解决方案1】:

    我认为 SwiftUI 目前不支持没有关闭按钮的警报,但您可以创建一个自定义视图并以相同的效果呈现它。

    这个库可能会帮助你:https://github.com/exyte/PopupView

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 1970-01-01
      • 2020-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多