Ios 以编程方式添加标签,与故事板中的标签对齐

Ios 以编程方式添加标签,与故事板中的标签对齐,ios,uitableview,autolayout,swift2,ios9,Ios,Uitableview,Autolayout,Swift2,Ios9,所需视图: 在情节提要中,我在Autolayout中创建了两个蓝色背景的标签。他们的立场永远不会改变。接下来,我想在蓝色背景标签下方的cellforrowatinexpath代码中添加1到10个标签 我正在努力将代码中添加的标签(棕色背景)与自动布局中创建的标签(蓝色背景)对齐 以下是我失败的尝试: 失败的两种方法: 在cellforrowatinexpath中,获取“B自动布局静态标签”的框架,并使用X位置作为动态标签。不起作用 添加约束也不起作用——也许我没有正确地添加约束 代码如下:

所需视图:

在情节提要中,我在Autolayout中创建了两个蓝色背景的标签。他们的立场永远不会改变。接下来,我想在蓝色背景标签下方的
cellforrowatinexpath
代码中添加1到10个标签

我正在努力将代码中添加的标签(棕色背景)与自动布局中创建的标签(蓝色背景)对齐

以下是我失败的尝试:

失败的两种方法:

  • cellforrowatinexpath
    中,获取“B自动布局静态标签”的框架,并使用X位置作为动态标签。不起作用

  • 添加约束也不起作用——也许我没有正确地添加约束

  • 代码如下:

    class TableViewController: UITableViewController {
    
        var cellHeight = [Int: CGFloat]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.estimatedRowHeight = 85.0
            self.tableView.rowHeight = UITableViewAutomaticDimension
        }
    
        override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
            return 1
        }
    
        override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 4
        }
    
    
        override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
    
            let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! CustomCell
            let xLocation = cell.labelBStatic.frame.origin.x
            var yLocation = cell.labelBStatic.frame.origin.y
            let height = cell.labelBStatic.frame.size.height
    
            var startYLocation = yLocation + height + 20
            var i = 0
            if indexPath.row % 2 == 0 {
                i = 5
            } else {
                i = 7
            }
    
            while i < 10 {
                let aLabel = UILabel()
                aLabel.backgroundColor = UIColor.orangeColor()
                aLabel.text = "Label # \(i)"
                cell.contentView.addSubview(aLabel)
                addConstraints(aLabel, verticalSpacing: startYLocation)
                startYLocation += 20
                i++
            }
    
            print(startYLocation)
            cellHeight[indexPath.row] = startYLocation
            return cell
        }
    
        func addConstraints(labelView: UILabel, verticalSpacing: CGFloat) {
            // set Autoresizing Mask to false
            labelView.translatesAutoresizingMaskIntoConstraints = false
    
            //make dictionary for views
            let viewsDictionary = ["view1": labelView]
    
            //sizing constraints
            let view1_constraint_H:Array = NSLayoutConstraint.constraintsWithVisualFormat("H:[view1(>=50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
    
            labelView.addConstraints(view1_constraint_H)
    
            //position constraints
            let view_constraint_H:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[view1]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewsDictionary)
            let view_constraint_V:NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|-\(verticalSpacing)-[view1]", options: NSLayoutFormatOptions.AlignAllLeading, metrics: nil, views: viewsDictionary)
    
            view.addConstraints(view_constraint_H as! [NSLayoutConstraint])
            view.addConstraints(view_constraint_V as! [NSLayoutConstraint])
    
        }
    
            override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    
            if let height = cellHeight[indexPath.row] {
                return height
            }
            return 0
        }
    
    类TableViewController:UITableViewController{
    var cellHeight=[Int:CGFloat]()
    重写func viewDidLoad(){
    super.viewDidLoad()
    tableView.estimatedRowHeight=85.0
    self.tableView.rowHeight=UITableViewAutomaticDimension
    }
    重写func numberOfSectionsInTableView(tableView:UITableView)->Int{
    返回1
    }
    重写func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
    返回4
    }
    重写func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath)->UITableView单元格{
    让cell=tableView.dequeueReusableCellWithIdentifier(“cell”,forIndexPath:indexPath)作为!CustomCell
    设xLocation=cell.labelBStatic.frame.origin.x
    变量位置=cell.labelBStatic.frame.origin.y
    let height=cell.labelBStatic.frame.size.height
    变量startYLocation=Y位置+高度+20
    变量i=0
    如果indexath.row%2==0{
    i=5
    }否则{
    i=7
    }
    当我<10{
    设aLabel=UILabel()
    aLabel.backgroundColor=UIColor.orangeColor()
    aLabel.text=“标签(i)”
    cell.contentView.addSubview(阿拉贝尔)
    添加约束(阿拉贝尔,垂直间距:起始位置)
    起始位置+=20
    我++
    }
    打印(起始位置)
    cellHeight[indexPath.row]=startYLocation
    返回单元
    }
    func addConstraints(labelView:UILabel,垂直间距:CGFloat){
    //将自动调整大小掩码设置为false
    labelView.translatesAutoresizingMaskIntoConstraints=false
    //为视图制作词典
    让viewsDictionary=[“view1”:labelView]
    //大小限制
    让view1\u constraint\u H:Array=NSLayoutConstraint.constraintsWithVisualFormat(“H:[view1(>=50)]”,选项:NSLayoutFormatOptions(rawValue:0),度量:nil,视图:viewsDictionary)
    labelView.addConstraints(视图1_constraint_H)
    //位置约束
    let view_constraint_H:NSArray=NSLayoutConstraint.constraintsWithVisualFormat(“H:|-15-[view1]”),选项:NSLayoutFormatOptions(rawValue:0),度量值:nil,视图:viewsDictionary)
    让视图\u constraint\u V:NSArray=NSLayoutConstraint.constraintsWithVisualFormat(“V:|-\(垂直间距)-[view1]”,选项:NSLayoutFormatOptions.AlignAllLeading,度量值:nil,视图:viewsDictionary)
    view.addConstraints(查看\u constraint\u H as![NSLayoutConstraint])
    view.addConstraints(查看\u constraint\u V as![NSLayoutConstraint])
    }
    重写func tableView(tableView:UITableView,heightForRowAtIndexPath:nsindepath)->CGFloat{
    如果let height=cellHeight[indexPath.row]{
    返回高度
    }
    返回0
    }
    
    下面是故事板的设置(两个标签水平居中):


    问题:如何使我在
    CellForRowatineXpath中创建的动态标签与在
    故事板中创建的静态标签左对齐,以匹配顶部所需的视图?

    仅出于演示目的,我以编程方式添加了一个标签,您可以添加任意数量的标签,只需添加对比即可如果不正确,还需要将底部空间约束添加到单元格内的最后一个标签,以便单元格将根据标签高度自动调整大小

    按照我所做的步骤实现您的目标:

  • 访问cellForRowAtIndexPath:中的B AutoLayout静态标签,如果您已将UITableViewCell子类化并已创建outlet,则使用标记或outlet

    let labelBAutolayoutStaticLabel = cell?.viewWithTag(20)
    
  • 按如下程序创建标签,并将TranslatesAutoResizengMaskinToConstraints设置为false

    let labelDynamicLabel = UILabel()
    labelDynamicLabel.backgroundColor = UIColor.orangeColor()
    labelDynamicLabel.text = "A Dynamic Label"
    labelDynamicLabel.translatesAutoresizingMaskIntoConstraints = false
    cell?.contentView.addSubview(labelDynamicLabel)
    
  • 您需要创建两个约束,一个用于TopSpace,另一个用于LeadingSpace,如下所示

    let leadingSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0);
    
    let topSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10); //Constant is the spacing between
    
    cell?.contentView.addConstraint(leadingSpaceConstraint)
    cell?.contentView.addConstraint(topSpaceConstraint)
    
    let views = ["cell": cell, "labelDynamicLabel": labelDynamicLabel, "labelBAutolayoutStaticLabel": labelBAutolayoutStaticLabel]
    
    let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelBAutolayoutStaticLabel]-[labelDynamicLabel]-|", options: [], metrics: nil, views: views)
    
    cell.contentView.addConstraints(verticalConstraints)
    
  • 将约束添加到单元格的contentView,如下所示

    let leadingSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0);
    
    let topSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10); //Constant is the spacing between
    
    cell?.contentView.addConstraint(leadingSpaceConstraint)
    cell?.contentView.addConstraint(topSpaceConstraint)
    
    let views = ["cell": cell, "labelDynamicLabel": labelDynamicLabel, "labelBAutolayoutStaticLabel": labelBAutolayoutStaticLabel]
    
    let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelBAutolayoutStaticLabel]-[labelDynamicLabel]-|", options: [], metrics: nil, views: views)
    
    cell.contentView.addConstraints(verticalConstraints)
    
  • 就这样

    这是结果

    以下是cellForRowAtIndexPath的完整代码:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell")
    
        let labelBAutolayoutStaticLabel = cell?.viewWithTag(20)
    
    
        let labelDynamicLabel = UILabel()
        labelDynamicLabel.backgroundColor = UIColor.orangeColor()
        labelDynamicLabel.text = "A Dynamic Label"
        labelDynamicLabel.translatesAutoresizingMaskIntoConstraints = false
        cell?.contentView.addSubview(labelDynamicLabel)
    
        let leadingSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0);
    
        let topSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10);
    
        cell?.contentView.addConstraint(leadingSpaceConstraint)
        cell?.contentView.addConstraint(topSpaceConstraint)
    
        return cell!
    }
    
    编辑/更新:

    如果必须将底部空间约束设置为最后一个标签(位于单元格底部的标签),则有两种方法

  • 使用NSLayoutConstraint如下所示:

    let bottomSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: -8)
    
    cell.contentView.addConstraint(bottomSpaceConstraint)
    
  • 使用可视化格式语言,如下所示

    let leadingSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0);
    
    let topSpaceConstraint: NSLayoutConstraint = NSLayoutConstraint(item: labelDynamicLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: labelBAutolayoutStaticLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 10); //Constant is the spacing between
    
    cell?.contentView.addConstraint(leadingSpaceConstraint)
    cell?.contentView.addConstraint(topSpaceConstraint)
    
    let views = ["cell": cell, "labelDynamicLabel": labelDynamicLabel, "labelBAutolayoutStaticLabel": labelBAutolayoutStaticLabel]
    
    let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[labelBAutolayoutStaticLabel]-[labelDynamicLabel]-|", options: [], metrics: nil, views: views)
    
    cell.contentView.addConstraints(verticalConstraints)
    
  • 如果使用VFL设置约束,请确保删除topSpaceConstraint

    //cell.contentView.addConstraint(topSpaceConstraint)
    
    这个“V:[LabelAutoLayoutStaticLabel]-[labelDynamicLabel]-|”字符串的意思是

  • labelDynamicLabel应具有顶部空间到LabelAutoLayoutStaticLabel的标准间距(8pts),labelDynamicLabel应具有底部空间到SuperView的标准间距。(“-|”表示SuperView的标准间距)

  • 谢谢。我想这应该行得通。我会在几个小时后尝试并报告。我这样添加了底部约束
    let bottomSpaceConstraint:NSLayoutConstraint=NSLayoutConstraint(项:lastLabel,属性:nslayouttribute.bottom,relatedBy:nslayouttribute.Equal,to项:lastLabel.superview,属性:nslayouttribute