簡體   English   中英

如何在沒有按鈕的情況下在 SwiftUI 中顯示警報

[英]How to present an Alert in SwiftUI with no buttons

我有一種情況,我想通過在用戶無法與之交互的長時間運行操作期間顯示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 arguments,發送了一個空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 ,要么使用不同的效果來指示狀態。 但是,我很想在這里錯了。

我不認為 SwiftUI 目前支持沒有關閉按鈕的警報,但您可以創建自定義視圖並以相同的效果呈現它。

這個庫可能會幫助你: https://github.com/exyte/PopupView

你可以試試這個:

    var dialogMessage = UIAlertController(title: "Erro", message: "error description", preferredStyle: .alert)
        let window = UIApplication.shared.keyWindow
        window?.rootViewController?.present(dialogMessage, animated: true)
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM