簡體   English   中英

SwiftUI | 如何在警報 window 中隱藏取消按鈕?

[英]SwiftUI | How to hide cancel button in alert window?

在 iOS 15( 文檔) 中測試新的alert方法時,我發現警報有一個奇怪的行為。

描述

這是代碼:

import SwiftUI

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            Button("button2", role: .destructive, action: {})
        }
    }
}

如您所見,我只添加了 2 個按鈕,但 SwiftUI 只是在按鈕末尾添加了Cancel按鈕。

但是,當任何按鈕沒有作用時,它就不會發生。


import SwiftUI

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            
            Button(action: {}) {
                Text("button1")
            }
        }
    }
}

這真的很奇怪。 我什至不知道它是 Apple 的意圖還是只是一個錯誤。

問題

因此,我的問題是,在添加了具有角色的按鈕后,如何刪除該取消按鈕。 有什么辦法可以做到這一點,或者我必須接受它..

任何建議將被認真考慮。

由於角色破壞按鈕用於刪除用戶數據,或根據 Apple 文檔執行不可逆轉的操作。

在警報視圖中可能是因為您有一個角色為 .破壞性的按鈕,所以警報默認添加一個.destructive按鈕。 要關閉警報,您應該定義一個角色.cancel的按鈕

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            Button("button2", role: .cancel, action: {})
        }
    }
}

結果

暫無
暫無

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

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