首页 > 解决方案 > SwiftUI - 如何创建带有标题和详细信息标签的列表?

问题描述

我正在尝试重新创建一个带有标题标签和详细标签的列表视图,就像许多标准 iOS 应用程序一样:

https://developer.apple.com/documentation/uikit/uitableviewcell/1623273-detailtextlabel

我想要左边的标题标签,右边的详细标签?有没有在 SwiftUI 中构建 UI 的标准实现?

谢谢!

标签: iosswiftxcodeswiftuixcode11

解决方案


为了代码简洁,我将这个小任务的不同部分分开。

每个单元格数据的模型:

struct CellModel {
    let title: String
    let detail: String
}

表示每个单独单元格的视图:

struct DetailCellView: View {

    let model: CellModel

    var body: some View {
        HStack() {
            Text(model.title)
            Spacer()
            Text(model.detail)
        }
    }
}

和列表(表)视图:

struct ContentView : View {

    // Data Source
    let cells = [
        CellModel(title: "Text 1", detail: "Detail 1"),
        CellModel(title: "Text 2", detail: "Detail 2"),
        CellModel(title: "Text 3", detail: "Detail 3")
    ]

    var body: some View {

        List(cells.identified(by: \.title)) { model in
            DetailCellView(model: model)
        }

    }
}

- 默认细节样式

如果您想要一个简单的默认详细信息构建器,请执行以下操作:

struct DetailCellView: View {

    @State var image: UIImage = UIImage()
    @State var title: String = ""
    @State var detail: String = ""

    var body: some View {
        HStack() {
            Image(uiImage: image)
            Text(title)
            Spacer()
            Text(detail)
        }
    }
}

推荐阅读