as diu
as diu

Reputation: 1090

How to add a label and UIButton to a tableViewSection header in Swift?

I have written the following code for adding a text label in the center of the section header view.

Second half of the code is to add a UIButton whose width is 100 and aligned to the right corner of the section header.

The result is: only the label added shows up at the center. The button does not show up on header at all!

Could you please help pointing out where I'm going wrong in the implementation? Thank you.

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView()

    // code for adding centered title
    headerView.backgroundColor = UIColor.gray
    let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width:
        tableView.bounds.size.width, height: 28))
    headerLabel.textColor = UIColor.black
    headerLabel.text = titlesList[section]
    headerLabel.textAlignment = .center
    headerView.addSubview(headerLabel)

    // code for adding button to right corner of section header        
    let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)) 
    showHideButton.setTitle("Show Closed", for: .normal)
    showHideButton.backgroundColor = UIColor.blue
    showHideButton.addTarget(self, action: #selector(btnShowHideTapped), for: .touchUpInside)

    headerView.addSubview(showHideButton)

    return headerView
}

Upvotes: 1

Views: 4240

Answers (2)

Bruno Rocha
Bruno Rocha

Reputation: 998

let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28)

The X position of your button is the size of the headerView minus 100. But your headerView has no frame (let headerView = UIView()) , which means it's width is 0. Thus your button is positioned at X -100.

I suppose you made a typo, and meant to position it based on the Table's width:

let showHideButton: UIButton = UIButton(frame: CGRect(x:tableView.bounds.size.width - 100, y:0, width:100, height:28)

Upvotes: 1

Rashwan L
Rashwan L

Reputation: 38833

Your problem is this row:

let headerView = UIView()

You have not specified any frame size and therefore the row below won´t be a recognized size for your showHideButton frame:

let showHideButton: UIButton = UIButton(frame: CGRect(x:headerView.frame.size.width - 100, y:0, width:100, height:28))

Use this row instead when you declare your headerView:

let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 100)) 

This will show the following: enter image description here

Upvotes: 2

Related Questions