Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add bottom border to tableview section header

I'm using the following function to determine the tableview section header in my app:

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
    var title: UILabel = UILabel()
     title.text = "something" 
     // Add a bottomBorder
     var border = UIView(frame: CGRectMake(0,0,self.view.bounds.width,1))
     border.backgroundColor = UIColor.redColor()
     title.addSubview(border)
}

and the following section to determine the tableview section header height:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat

How can I add a bottom border to the section?

like image 844
Dor Cohen Avatar asked May 26 '15 13:05

Dor Cohen


2 Answers

You can create UIView which will act as a border and then add it:

var border = UIView(frame: CGRectMake(0,40,self.view.bounds.width,1))
border.backgroundColor = UIColor.redColor()
headerView.addSubview(border)

headerView is your custom view that you actually create

EDIT

 var headerView = UIView(frame: CGRectMake(0,0,self.view.bounds.width,40))
 var title = UILabel(frame: CGRectMake(0, 0, 200, 21))
 title.text = "something" 
 // Add a bottomBorder
 var border = UIView(frame: CGRectMake(0,39,self.view.bounds.width,1))
 border.backgroundColor = UIColor.redColor()
 headerView.addSubview(border)
 headerView.addSubview(title)
 return headerView

EDIT

CGRectMake is not available anymore from Swift 3.0. Use CGRect instead

like image 117
Miknash Avatar answered Oct 15 '22 09:10

Miknash


Swift 3

This worked for me. In viewForHeaderInSection:

  let headerView = UIView()

    let borderTop = UIView(frame: CGRect(x:0, y:0, width: tableView.bounds.size.width, height: 1.0))
    borderTop.backgroundColor = UIColor.self.init(red: 5/255, green: 16/255, blue: 28/255, alpha: 1.0)
    headerView.addSubview(borderTop)

    let borderBottom = UIView(frame: CGRect(x:0, y:40, width: tableView.bounds.size.width, height: 1.0))
    borderBottom.backgroundColor = UIColor.self.init(red: 5/255, green: 16/255, blue: 28/255, alpha: 1.0)
    headerView.addSubview(borderBottom)

You can adjust top and bottom position depending on you header high. y=0 for top and x=40 for bottom border works for me. Hopes this helps. Good luck.

If you want to customize the rest of the header:

 let headerLabel = UILabel(frame: CGRect(x: 15, y: 9, width: tableView.bounds.size.width, height: tableView.bounds.size.height))

    headerLabel.font = UIFont(name: "Trebuchet MS", size: 19)

    headerLabel.textColor = UIColor.self.init(red: 254/255, green: 170/255, blue: 25/255, alpha: 1.0)

    headerLabel.text = self.tableView(self.tableView, titleForHeaderInSection: section)

    headerLabel.sizeToFit()

    headerView.addSubview(headerLabel)
like image 45
Dian Avatar answered Oct 15 '22 09:10

Dian