水平对齐标签

时间:2015-05-25 15:51:13

标签: swift

如何生成随机数量的标签并将它们在中间彼此相邻?

我有这个代码来生成标签:

var label = UILabel(frame: CGRectMake(5, 196, 35,45 ))
    label.textAlignment = NSTextAlignment.Center
    label.backgroundColor = UIColor.redColor()
    label.text = "1";
    label.tag = 5;
    self.view.addSubview(label);

这项工作很完美,但我怎样才能生成多个标签并将它们设置在中间?

像这样:

enter image description here

或者,如果我生成3个标签,它必须如下所示: enter image description here

这可以通过编程方式进行吗?

1 个答案:

答案 0 :(得分:0)

这样做:

var lastLabel : UILabel?
var count = 1

@IBAction func addlabel(sender: AnyObject) {
    var label = UILabel()
    label.textAlignment = NSTextAlignment.Center
    label.backgroundColor = UIColor.redColor()
    label.text = count.description;
    count++
    label.tag = 5;


    var centerX = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
    centerX.priority = 999
    //This if you want to center it vertically also
    var centerY = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
    var height = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35)
    var width = NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 45)

    label.setTranslatesAutoresizingMaskIntoConstraints(false)
    self.view.addSubview(label);

    if let prevlabel = lastLabel {
        var align = NSLayoutConstraint(item: prevlabel, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: label, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: -20)
        //Here just add the NSLayoutConstraint you want to apply, if its only horizontal then not add  centerY

        NSLayoutConstraint.activateConstraints([align, centerY, height, width, centerX])
    }else {
        NSLayoutConstraint.activateConstraints([centerX, centerY, height, width])
    }
    lastLabel = label
}