如何在“viewForHeaderInSection”中为UILabel视图设置自动布局约束

9
 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紧贴在标头的右侧,看起来很糟糕。我需要一点间距。


1
将-20的值更改为20并尝试,但我认为这不会起作用,因为您只是使用标签。按照我的建议,您应该使用UIView,然后从标签向视图添加各种约束,并将UIView作为标题返回。 - Mahesh Agrawal
1个回答

11

我修改了你的代码,这是修改后的版本,请试一试。

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
}

1
translatesAutoresizingMaskIntoConstraints = false 对我来说真是太重要了。一定有很多时间浪费在这上面了。 - lewis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接