【发布时间】:2019-10-29 13:01:04
【问题描述】:
来自 React 背景很容易只在定义了值的情况下渲染视图。它看起来像这样:
function Component ({ profile }) {
return (
<div>{profile && <div>{profile.name}}</div>
)
}
但我发现在 SwiftUI 中复制这种模式要困难得多。理想情况下,我们可以在视图中使用条件展开,但这目前不起作用。我能想出的唯一解决方案真的很不优雅:
struct ProfileView : View {
var profile: Profile?
var body : some View {
if let profile = profile {
return Text("profile: \(profile.bio)")
} else {
return Text("")
}
}
}
struct LayoutView : View {
@State var profile: Profile?
var body : some View {
Group {
ProfileView(profile: profile)
}
}.onAppear(perform: fetch)
// fetch method
}
有没有人有一些更好的使用可选值进行条件渲染的策略?
【问题讨论】:
-
用
Text(profile != nil ? "profile: \(profile!.bio)" : "")替换整个if let块。这里没有特定于 SwiftUI 的内容。 -
天啊,我从来没有考虑过使用 !操作员。说到 Swift,我完全是个新手……显然,嘿。