Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a custom cell as header or footer of UITableView

I am using Xib files instead of storyboard. I have created a table view with some dummy data. Its working fine, Now I have created a custom cell with some labels and textFields. How can I use it as header or footer of UITableView ?

like image 629
Byte Avatar asked Jul 01 '16 07:07

Byte


2 Answers

The answer is actually pretty simple. In viewForHeaderInSection() create cell object as you do in cellForRowAtIndexPath() and return it.

Here is sample code.

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCellWithIdentifier("cellIdentifier") as! YourTableViewCell
    return cell
}

You can set height for header as:

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 80
} 

Update for Swift 4.2

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellIdentifier") as! YourTableViewCell
    return cell
}

and

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 80
}
like image 124
Tushar Korde Avatar answered Oct 02 '22 02:10

Tushar Korde


You can create a custom view programmatically. I tried the following code. Try it once.

override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let customview:UIView = UIView();
        let label = UILabel();
        label.text = "ur custom data"
        /*
            You can add any number of subviews you want here
            And don't forget to add it to your customview.
         */
        customview.addSubview(label)
        return customview;
    }

similarly you can do the same thing for header also.

like image 20
Ramcharan Reddy Avatar answered Oct 02 '22 02:10

Ramcharan Reddy