Akshaykumar Maldhure
Akshaykumar Maldhure

Reputation: 1259

Tableview multiple sections with one floating header

I wanted to implement table with sections, but I wanted only one section should have header, and for all section this single header should be displayed as floating.

Does anyone have solution for this, Please help me.

Upvotes: 0

Views: 837

Answers (2)

André Slotta
André Slotta

Reputation: 14040

I agree with SuperDuperTango to just use one section in that case. An easy way to transform your sectioned data source would be something like this:

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
    }

}

Upvotes: 2

SuperDuperTango
SuperDuperTango

Reputation: 1408

If I understand you correctly, you might try creating a UITableView with a single section (that has the floating header you're looking for). The downside to this is that you'll need to manage your indexPaths, which is kind of a pain.

For example, if you have 3 "sections", each section has 4 elements, then in "Section 0" of your tableView (IndexPath.section == 0), you'll have 12 rows (maybe 3 more if you want non-floating "header cells" (which would just be standard UITableViewCells.

Upvotes: 0

Related Questions