首页 > 解决方案 > 使用一个浮动标题查看多个部分

问题描述

我想用部分实现表格,但我希望只有一个部分应该有标题,并且对于所有部分,这个单个标题应该显示为浮动。

有没有人有解决方案,请帮助我。

标签: iosswifttableview

解决方案


我同意SuperDuperTango在这种情况下只使用一个部分。转换分段数据源的一种简单方法是:

struct Section {
    let title: String
    let rows: [Row]
}

struct Row {
    let title: String
}

class TableViewController: UITableViewController {

    // original data source
    let sections: [Section] = {
        var sections = [Section]()

        for section in ["A", "B", "C", "D", "E"] {
            let numberOfRows = 1...Int.random(in: 1...5)
            let rows = numberOfRows.map { Row(title: "Section \(section), Row \($0)") }
            let section = Section(title: "Section \(section)", rows: rows)
            sections.append(section)
        }

        return sections
    }()

    // transformed data source
    var allRows: [Row] {
        return sections.reduce([], { $0 + $1.rows })
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Your section title"
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allRows.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = allRows[indexPath.row].title
        return cell
    }

}

推荐阅读