Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set an auto layout constraint in "viewForHeaderInSection" for a UILabel view

 func tableView(tableView:UITableView, viewForHeaderInSection section:Int) -> UIView?{
        let newlabel = UILabel()
        //206-250

        newlabel.backgroundColor = UIColor(red: (135/255), green:(206/255), blue: (250/255), alpha: 1)
        newlabel.textColor = UIColor(white: 1, alpha: 1)
        newlabel.textAlignment = .Right
        newlabel.font = newlabel.font.fontWithSize(18)
        newlabel.adjustsFontSizeToFitWidth = true
        let horizontalcontraint = NSLayoutConstraint(item: newlabel, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -20)
        NSLayoutConstraint.activateConstraints([horizontalcontraint])

        newlabel.constraints
        newlabel.text = keys[section]+" - "
        return newlabel
    }

I'm not sure how to reference the section header in the toItem: part of the constraint. Any advice would be appreciated. The UILabel is pinned up against the right side of the header and looks bad. I need a little spacing in there.

like image 806
BostonMacOSX Avatar asked Sep 19 '16 01:09

BostonMacOSX


1 Answers

I have modified your code and here it is. Try once.

func tableView(tableView:UITableView, viewForHeaderInSection section:Int) -> UIView?{
    let headerView = UIView()
    headerView.backgroundColor = UIColor.clearColor()
    let newlabel = UILabel()
    //206-250

    newlabel.backgroundColor = UIColor(red: (135/255), green:(206/255), blue: (250/255), alpha: 1)
    newlabel.textColor = UIColor(white: 1, alpha: 1)
    newlabel.textAlignment = .Right
    newlabel.font = newlabel.font.fontWithSize(18)
    newlabel.adjustsFontSizeToFitWidth = true

    newlabel.constraints
    newlabel.text = keys[section]+" - "

    headerView.addSubview(newlabel)
    newlabel.translatesAutoresizingMaskIntoConstraints = false
    headerView.addConstraint(NSLayoutConstraint(item: newlabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: headerView, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 0))
    headerView.addConstraint(NSLayoutConstraint(item: newlabel, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: headerView, attribute: NSLayoutAttribute.Trailing, multiplier: 1.0, constant: 20.0))
    headerView.addConstraint(NSLayoutConstraint(item: newlabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: headerView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0))
    headerView.addConstraint(NSLayoutConstraint(item: newlabel, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: headerView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0))

    return headerView
}
like image 198
Mahesh Agrawal Avatar answered Nov 16 '22 00:11

Mahesh Agrawal