gpt4 book ai didi

ios - 在 SwiftUI 中显示一个空 View

转载 作者:行者123 更新时间:2023-12-01 15:22:01 24 4
gpt4 key购买 nike

在 SwiftUI 中,经常需要根据某些条件显示“空” View ,例如:

struct OptionalText: View {
let text: String?

var body: some View {
guard let text = text else { return }

return Text(text)
}
}

不幸的是,由于 guard 的主体,这不能编译。必须返回一些 View ,即 text 时的“空” View 是 nil .应该如何重写此示例,以便在 text 时编译并呈现“空” View 是 nil ?

最佳答案

你必须返回一些东西。如果在某些情况下您不想显示任何内容,请“显示”... EmptyView ;)

var body: some View {
Group {
if text != nil {
Text(text!)
} else {
EmptyView()
}
}
}

SwiftUI DSL 将要求您将 if/else 包装在 Group 中。并且 DSL 没有 guard /if let 命名法。

关于ios - 在 SwiftUI 中显示一个空 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60988527/

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