SwiftUI 列表 header 和子 header

SwiftUI List header and subheader

我的目标是让 List 部分带有粗体 header 和 non-bold sub-header,但我不知道该怎么做做。因此,我尝试使用 Text 视图制作 header,该视图包含部分粗体文本和部分普通 non-bold 文本。

我试着用 NSAttributedString 来做这个,它与 UILabel 一起工作,但它似乎不适用于 swiftUI 的 Text object.

我是这样制作 header 的:

Section(header: Text(docSection.formattedHeader)) {
    ...

其中 docSection.formattedHeader 是半粗体的 NSAttributedString,半 non-bold 用 \n

分隔

但是我收到以下错误:

Initializer 'init(_:)' requires that 'NSAttributedString' conform to 'StringProtocol'

有没有办法实现这个?

由于 NSAttributedStringSwiftUI 不兼容(目前),您应该改用 Text。但是对于Section,你可以使用任意的View。那么你为什么不用这样的stackView

Section(header:
    VStack(alignment: .leading) {
        Text("Header").fontWeight(.bold)
        Text("Subheader").fontWeight(.regular)
    }
) {
    Text("Content")
}

您也可以使用 HStack 或任何其他组合视图。