我正在尝试向单元格添加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.
我查看了以下帖子:Swift, Constraint, The view hierarchy is not prepared for the constraint,Why is my layout constraint returning an error in this case? (Swift)和Swift, Constraint, The view hierarchy is not prepared for the 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
}
非常感谢你的帮助:)
答案 0 :(得分:1)
序列是:
translatesAutoresizingMaskIntoConstraints
设为false
; addSubview
将其添加到视图层次结构中;和如果您正在使用约束,请勿设置frame
。一切都应该由约束来定义。
调用dequeueReusableCellWithIdentifier
然后添加子视图可能并不谨慎。如果重复使用该单元怎么办?您将多次添加相同的子视图。如果来自故事板或NIB,则可能最好将编程添加子视图放在awakeFromNib
的单元子类实现中,或者init(style;, reuseIdentifier)
如果以编程方式构建它。或者,最简单,不要以编程方式创建单元格并使用故事板或NIB。
答案 1 :(得分:0)
在以编程方式向任何视图添加约束之前,您应将其添加为子视图并将translatesAutoresizingMaskIntoConstraints转换为false,然后添加所需的约束。像
cell.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
//now add your required constraints