如何在没有按钮的 SwiftUI 中呈现警报

Cod*_*der 5 ios ios13 swiftui swiftui-alert

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

以前在 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)
    }
}
Run Code Online (Sandbox Code Playgroud)

它看起来像这样:

在此输入图像描述

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)
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

无论我使用nilor.none作为dismissButton参数,还是完全省略该行,它都会使用默认OK按钮,并生成以下内容:

在此输入图像描述

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

dismissButton: .default(Text("")))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

根据我所看到的,根据检查其初始值设定项,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)
Run Code Online (Sandbox Code Playgroud)

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

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

Lua*_*lan 0

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

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