gpt4 book ai didi

swift - 使用 SwiftUI 在条件内显示警报

转载 作者:行者123 更新时间:2023-12-04 16:42:24 25 4
gpt4 key购买 nike

我知道 Alert 可以作为 Button 的函数呈现,但是 Alert 可以在条件中呈现吗?如:

struct ContentView: View {

var body: some View {
Text("Hello World!")
}
}

if isValid {

//present alert
let alert = UIAlertController(title: "My Title", message: "This
is my message.", preferredStyle: UIAlertController.Style.alert)

alert.addAction(UIAlertAction(title: "OK", style:
UIAlertAction.Style.default, handler: nil))

self.present(alert, animated: true, completion: nil)
}

这样我就明白了

Value of type 'ContentView' has no member 'present'

最佳答案

我不确定你为什么要使用 UIKit。这是一个示例,说明当某些内容更改标志时如何显示警报。在这种情况下,一个两秒的计时器:

import SwiftUI

class MyModel: ObservableObject {
@Published var isValid: Bool = false

init() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
self.isValid = true
}
}
}

struct ContentView: View {
@ObservedObject var model: MyModel = MyModel()

var body: some View {
VStack {
Text("Some text")
Text("Some text")
Text("Some text")
Text("Some text")
}.alert(isPresented: $model.isValid, content: {
Alert(title: Text("Title"),
message: Text("Message"),
dismissButton: .default(Text("OK")) { print("do something") })
})
}
}

关于swift - 使用 SwiftUI 在条件内显示警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com