2016-09-19 85 views
1
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 
    } 

我不确定如何引用约束的toItem:部分中的节标题。任何意见,将不胜感激。 UILabel被固定在标题的右侧,看起来很糟糕。我需要一点点空间。如何在“viewForHeaderInSection”中为UILabel视图设置自动布局约束

+1

更改-20到20的值,尝试但我认为它不会工作,因为你只是使用标签。根据我的说法,你应该使用UIView,然后将所有约束王从标签添加到视图中,并返回UIView作为标题。 –

回答

2

我修改了你的代码,就在这里。尝试一次。

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 
} 
+0

感谢代码...从中学到了很多东西。 – BostonMacOSX

+0

很高兴我的回答帮助你.. –