繁体   English   中英

在表格视图单元格中添加自动布局约束。

[英]Adding auto layout constraints in a tableview cell.

我试图将UIImageView添加到单元格并以编程方式添加自动布局约束。 但是,这给了我以下错误: The view hierarchy is not prepared for the constraint... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. The view hierarchy is not prepared for the constraint... When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. 我查看了以下几篇文章: Swift,Constraint,未为该约束准备视图层次结构在这种情况下为什么我的布局约束返回错误? (Swift)Swift,Constraint,视图层次结构没有为约束准备 我不能添加到这些帖子建议我添加的代码中的一件事是setTranslatesAutoresizingMaskIntoConstraints 当我尝试将此功能添加到imageView ,出现错误。

这是我的代码:

    func cellTwo(indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("cellTwo", forIndexPath: indexPath) as! CathyTaskLogTwoTableViewCell

        let imageView:UIImageView = UIImageView(image: UIImage(named: "defaultPicture"))
        imageView.frame.size.width = 100
        imageView.frame.size.height = 31
                let horizonalContraints = NSLayoutConstraint(item: imageView, attribute:
            .LeadingMargin, relatedBy: .Equal, toItem: cell,
            attribute: .LeadingMargin, multiplier: 1.0,
            constant: 20)
        imageView.addConstraint(horizonalContraints)

        cell.addSubview(imageView)

        return cell

    }

提前非常感谢您的帮助:)

  1. 顺序为:

    • 实例化子视图(例如图像视图);
    • 设置translatesAutoresizingMaskIntoConstraintsfalse ;
    • 调用addSubview将其添加到视图层次结构中;
    • 添加约束。
  2. 如果使用约束,则根本不要设置frame 一切都应由约束条件来定义。

  3. 调用dequeueReusableCellWithIdentifier然后添加一个子视图可能并不明智。 如果该单元被重用怎么办? 您将多次添加相同的子视图。 子视图的编程添加可能最好放在awakeFromNib的单元子类实现中(如果从情节提要或NIB中实现),或者如果以编程方式构建,则将其放入init(style;, reuseIdentifier) 或者,最简单的是,根本不以编程方式创建单元并使用情节提要或NIB。

在以编程方式将约束添加到任何视图之前,应将其添加为子视图,并将translatesAutoresizingMaskIntoConstraints设置为false,然后添加所需的约束。 喜欢

 cell.addSubview(imageView)
 imageView.translatesAutoresizingMaskIntoConstraints = false

 //now add your required constraints

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM