Nico
Nico

Reputation: 6359

How to make the first row of an UITableView a header of a section?

I have an UITableView with custom cells. I would like that the first row is always visible. As I have only once section, I thought of making a header but in this case I don't really know how to do it?

Is it possible to make a header from the first row with the same gesture recognizers, same dataSource behind the rows, briefly, have the header exactly like th row, just as if the row was pined to the top of the tableView?

Upvotes: 0

Views: 6318

Answers (2)

Wez
Wez

Reputation: 10712

If you want to make one static cell that is pinned to the top but in all other ways the same to the others, you could simply add one to your numberOfRowsInSection

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataSource.count + 1
}

Then when you display the cells, check for the row number and always set the first row to contain your static header content.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    if indexPath.row == 0 {
        // Create or set static cell content.
    }
}

The other way is to create a custom section header and set it using viewForHeaderInSection

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 0 {
        var view = UIView()
        view.backgroundColor = UIColor.blueColor()
        return view
    }
    return nil
}

Upvotes: 1

Wain
Wain

Reputation: 119031

You should use a header, or a separate view outside the table view. You can use the same gestures (generally, though not the delete) and data source.

If you want it all, you could use 2 table views- the first with one section and one row, the second with all the other data. It would be easiest if your data source was broken down in a similar way in the view controller.

In either case you can achieve what you want, but not by flicking a switch, you will need to add some logic and different views to make it happen.

Upvotes: 3

Related Questions