UITabel里面嵌套的UIStackViews内的UILabel有时会截断

时间:2017-07-04 19:27:47

标签: ios uitableview autolayout uilabel uistackview

我的一个表设置中的tableview单元格包含以下视图层次结构

TableView Cell view hierarchy

外部水平堆栈视图固定在单元格的尾部,前导,底部和顶部边缘的内容视图中。

正确的标签固定在其尾部,前导,底部和顶部边缘的父堆栈ViewHackView

在我的控制器代码中,我将单元格设置为动态高度以适应单元格的内容,以便它们可以根据内容大小增大或缩小

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 30.0 

关于自动布局设置。 ( BOLD 中的相关优先级)

  • 外部水平堆栈视图
    • 内容拥抱优先级== 250
    • 内容压缩阻力优先级== 750
    • 内部垂直堆栈视图
      • 内容拥抱优先级== 750
      • 内容抗压缩优先级== 750
      • 左标签1
        • 内容拥抱优先级== 750
        • 内容抗压缩优先级== 750
      • 左标签2
        • 内容拥抱优先级== 750
        • 内容抗压缩优先级== 750
      • 查看(只是将两个左侧标签填充到堆栈视图的顶部)
        • 内容拥抱优先级== 250
        • 内容压缩阻力优先级== h:750; v:250
    • stackViewHackView(破解使多行标签在堆栈视图和单元格内正常生长)
      • 内容拥抱优先级== 250
      • 内容压缩阻力优先级== h:250; v:750
        • 降低水平阻力以允许此视图压缩左侧堆栈视图以适合
    • 右标签
      • 内容拥抱优先级== 250
      • 内容压缩阻力优先级== h:250; v:750
        • 降低水平阻力以允许此视图压缩左侧堆栈视图以适合

我在一个简单的测试应用程序中使用以下代码

填充此单元格中的测试数据
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell 
{
  let cell = tableView.dequeueReusableCell(withIdentifier: "testCell", for: indexPath) as! TestTableViewCell


  // Configure the cell...

  if indexPath.section == 0
  {
    cell.leftLabel1?.text = "Label1 aabbccdd"
    cell.leftLabel2?.text = "Label2 aabbccdd"
    cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
  }
  else if indexPath.section == 1
  {
    cell.leftLabel1?.text = "Label1 aabbccdd"
    cell.leftLabel2?.text = "Label2 aabbccdd"
    cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
  }
  else
  {
    cell.leftLabel1?.text = "Label1 aabbccdd"
    cell.leftLabel2?.text = "Label2 aabbccdd"
    cell.rightLabel?.text = "Cell \(indexPath.row) with a 'really really really really really really really really' long string that needs displaying clearly and causing the table cell to resize to fit the content. We're looking for about 3 or 4 lines of text to be displayed"
  }

  return cell
}

这导致在iPhone 7目标上的模拟器中进行以下渲染

Simulator screenshot

中间的tableview单元格是我想要一直得到的那种输出。我不希望左侧标签被截断,它们的内容总是小到足以与右侧配合。然而,鉴于右侧的某些内容,有时可以截断较长的标签2,如您在顶部和底部行中所看到的那样。

我设置了内容抗压力,使得左侧的所有元素都具有高抗压性,右侧的元素设置为较低的阻力,因此它们应该压缩以为左侧元素留出空间。

为什么会发生这种情况或我如何阻止它发生这样的任何想法,以便我的标签始终正确显示?

干杯!

1 个答案:

答案 0 :(得分:1)

(根据OP添加为答案)

这可能只是“我看起来如何”但是......我看到很多人使用堆栈视图中的堆栈视图包装在堆栈视图中,当有限制的简单视图可以完成工作时。

看看我在这个项目中是如何做到的:github.com/DonMag/CellTest2

这非常简单,您可以查看标签,看看我在改变优先级方面做得多么少。我使用了您的示例字符串,并添加了一些案例来测试变体。

相关问题