如何在SwiftUI中显示没有按钮的警报

时间:2020-06-30 15:13:19

标签: ios swiftui ios13 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)
    }
}

它看起来像这样:

enter image description here

可以这样创建一个简单的基于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按钮并产生以下内容:

enter image description here

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

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

enter image description here

根据我所看到的,基于检查其初始化程序,SwiftUI中的Alert似乎并没有支持我想要的。

/// 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,但这似乎是我们无法获得预期结果的场景。

我的理解是要么我们不得不引入基于AlertController的UIKit,要么使用其他效果来指示状态。但是,我很想在这里弄错。

1 个答案:

答案 0 :(得分:0)

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

该库可能会帮助您:https://github.com/exyte/PopupView

相关问题