【发布时间】:2022-06-23 12:35:55
【问题描述】:
我正在尝试编写一个扩展程序,在其下方添加一个标题(我称之为statusBar),无论标题是什么类型(例如文本、图像、链接......)。所以我尝试了下面的代码。但是 Xcode 在.statusBar 之前的那行说Type '()' cannot conform to 'View' 的错误。您可以在下面的代码中找到我添加的注释。
我知道我的.statusBar 中一定有问题,因为当我用单个视图替换 if-let-else 块时错误消失了(例如 Text("Hello, world!"))。但我仍然想根据那个 if-let 语句显示不同的内容。那么我该如何使用我的代码来解决这个问题呢?
// .statusBar extension
struct StatusBarView: ViewModifier {
let statusBar: AnyView
init<V: View>(statusBar: () -> V) {
self.statusBar = AnyView(statusBar())
}
func body(content: Content) -> some View {
VStack(spacing: 0) {
content
statusBar
}
}
}
extension View {
func statusBar<V: View>(statusBar: () -> V) -> some View {
self.modifier(StatusBarView(statusBar: statusBar))
}
}
// Inside main app view
Image(systemName: "link")
.font(.system(size: 48)) // Xcode error: Type '()' cannot conform to 'View'
.statusBar {
//
// If I change below if-let-else to a single view
// (e.g. Text("Hello, world!"))
// Then it works.
//
if let url = mediaManager.url {
Text(url.path)
} else {
Text("No media loaded.")
}
}
【问题讨论】: