SwiftUI节中的可选页眉和页脚,不透明返回类型错误



我试图实现的是在ListView中有不同的部分,这些部分可能有页脚或页眉文本可见,也可能没有。由于Section的类型严格要求有一个页脚或一个页眉,或者两者都有,或者没有,所以我必须遍历所有情况才能创建下面代码中的部分。我遇到的问题是body给出了错误Function declares an opaque return type, but the return statement in its body do not have matching underlying types,所以根据我的理解,它希望有一个唯一的返回类型,我认为这不是我想要的情况。我是SwiftUI的新手,不知道在这种情况下如何纠正这个问题。同样,在最后一种情况下返回nil会抱怨'nil' requires a contextual type。非常感谢。

struct CMGeneralSettingsSectionView: View {
@Binding var section: CMGeneralSettingsSection
var body: some View {
if let headerTitle = section.headerTitle {
if let footerTitle = section.footerTitle {
return Section(header: Text(headerTitle),
footer: Text(footerTitle)) {
return Text("")
}
} else {
return Section(header: Text(headerTitle)) {
return Text("")
}
}
} else {
if let footerTitle = section.footerTitle {
return Section(footer: Text(footerTitle)) {
return Text("")
}
} else {
return nil
}
}
}
}

制作body视图生成器并返回EmptyView而不是nil,这是不允许的,因为some View返回类型不是可选的。

这里是固定变体

struct CMGeneralSettingsSectionView: View {
@Binding var section: CMGeneralSettingsSection
@ViewBuilder
var body: some View {
if let headerTitle = section.headerTitle {
if let footerTitle = section.footerTitle {
return Section(header: Text(headerTitle),
footer: Text(footerTitle)) {
return Text("")
}
} else {
return Section(header: Text(headerTitle)) {
return Text("")
}
}
} else {
if let footerTitle = section.footerTitle {
return Section(footer: Text(footerTitle)) {
return Text("")
}
} else {
return EmptyView()
}
}
}
}

Section有一个名为init(content:header:footer:)(iOS 13+(的初始化程序。

以下代码片段显示了init(content:header:footer:)的可能实现,以便根据可选值显示或不显示页眉和/或页脚:

struct CMGeneralSettingsSection {
var headerTitle: String?
var footerTitle: String?
}
import SwiftUI
struct CMGeneralSettingsSectionView: View {
@Binding var section: CMGeneralSettingsSection
var body: some View {
Section {
Text("Content")
} header: {
if let headerTitle = section.headerTitle {
Text(headerTitle)
}
} footer: {
if let footerTitle = section.footerTitle {
Text(footerTitle)
}
}
}
}
import SwiftUI
struct ContentView: View {
@State var generalSettingsSection = CMGeneralSettingsSection(
headerTitle: "Title", 
footerTitle: "Footer"
)
var body: some View {
NavigationView {
Form {
CMGeneralSettingsSectionView(section: $generalSettingsSection)
}
}
}
}

最新更新