什么约束会阻止我的UIView堆叠在一起呢?

我的UIView是堆叠在一起,像这样:

在这里输入图像说明

每个UIView都在wordContainer 。 每个UIView都有两个UILabel

我创build每个单独的UIView与两个孩子UILabel的是这样的:

  var labels = [UIView]() for word in words { let wordLabel = UILabel(frame: CGRectZero) wordLabel.text = word.valueForKey("sanskrit") as? String wordLabel.numberOfLines = 0 wordLabel.sizeToFit() wordLabel.translatesAutoresizingMaskIntoConstraints = false let englishWordLabel = UILabel(frame: CGRectMake(wordLabel.frame.width + 10,0,0,0)) englishWordLabel.text = word.valueForKey("english") as? String) englishWordLabel.numberOfLines = 0 englishWordLabel.sizeToFit() englishWordLabel.lineBreakMode = .ByWordWrapping englishWordLabel.translatesAutoresizingMaskIntoConstraints = false let wordView = UIView(frame: CGRectMake(0,0,self.view.frame.width,englishWordLabel.frame.height)) wordView.translatesAutoresizingMaskIntoConstraints = false wordView.addSubview(wordLabel) wordView.addSubview(englishWordLabel) wordView.sizeToFit() labels.append(wordView) } 

然后我把这个UIView的集合添加到我的wordContainer 。 这是我想象中的部分,我应该设置NSLayoutConstraints。 这个想法是,我希望他们都妥善堆叠在一起。 例如,它应该看起来像这样:

 word: definition word: definition word: definition word: definition 

但是看起来像这样:

在这里输入图像说明

我将它们添加到wordContainer如下所示:

  let wordContainer = UIView(frame: CGRectZero) var currentY:CGFloat = 0.0 let margin_height:CGFloat = 4.0 var height:CGFloat = 0 for view in wordViews { var rect = view.frame rect.origin.y = currentY view.frame = rect currentY += view.frame.height height += view.frame.height wordContainer.addSubview(view) } let containRect = CGRectMake(0,0,self.view.frame.width, height) wordContainer.frame = containRect 

然后,我为wordContainer设置了约束条件,如果它们不是堆叠在一起的话,它们可以有效地允许所有单词的空间存在:

  wordContainer.bottomAnchor.constraintEqualToAnchor(cell.contentView.bottomAnchor).active = true wordContainer.topAnchor.constraintEqualToAnchor(cell.contentView.topAnchor).active = true 

我最近的想法是,也许我应该增加约束。 我已经尝试添加NSLayoutConstraintscell的高度,当我做所有的单词不再适当地布局。 相反,它们堆叠在一起。 但是,这似乎是正确的方向..

为了让单元格自动调整高度,contentView内的内容必须对contentView的所有4条边进行约束。

我刚刚使用不同的文本,图像和embedded式推文的单元格types,并且遇到了一些您所描述的问题。 我发现最简单的方法是在内容视图中的任何组件上添加视图,然后您可以轻松地将约束添加到该元素四周。

我刚刚查看了一些可以certificate这一点的东西,并find了另外一个答案 ,用一些截图来解释它。

另外我今天使用的参考文献是Ray Wenderlich网站上的这篇文章

在您的UITableViewController ,在viewDidLoad() ,请尝试:

 //set up table view cell dynamic height tableView.rowHeight = UITableViewAutomaticDimension 

在故事板中,确保使用AutoLayout,并将单元格元素的所有约束条件都设置并修复。 例如,您的单元格的顶部文本必须有Superview定义的边距,并设置为一个值。