ios - 更改两个 UITableViewCells 之间的间距以匹配行间距

标签 ios swift uitableview autolayout uilabel

我有一个 UITableView 可以模拟编码界面。它必须是 UITableView

每一行代码都是一个UITableViewCell。由于代码行可能比 TableView 更长/更宽,因此我将其高度调整为内部 UILabel 的大小。

codeTableView.rowHeight = UITableViewAutomaticDimension //when creating the tableView

cell.textLabel?.numberOfLines = 0 //when creating the cell

这按预期工作。但是,单元格(或“代码行”)之间的差距当然比 cell.textLabel 的两行之间的差距大得多。

如何匹配这两个高度,使它们始终相同?澄清一下:我指的是一个 cell.textLabel 的两行与两个 tableViewCells 的最后一行和第一行之间的区别。它们应该相等。

这是我的情况的图片(单元格是青色,标签是绿色) enter image description here

使用约束的解决方案尝试

使用约束会导致标签被压缩。而且我不能用约束设置标签高度,因为它的高度需要变化(取决于行数)

cell.textLabel?.translatesAutoresizingMaskIntoConstraints = false
cell.textLabel?.topAnchor.constraint(equalTo: cell.topAnchor, constant: 20.0).isActive = true
cell.textLabel?.bottomAnchor.constraint(equalTo: cell.bottomAnchor, constant: -20.0).isActive = true

enter image description here (单元格为青色,标签为绿色)

问题是,约束将调整 label 而非单元格的大小。并且 label 高度无法使用约束来固定,因为它需要根据行数自由更改

最佳答案

一种方法:使用自动布局,将标签固定到 Top: 0Bottom: 0应该为您提供(有效地)单元格之间与多行之间相同的行间距。

我的原型(prototype)单元格...我将前导和尾部设置为 16,行数为零,因此较长的文本是自动换行(headIndent 为 32 的属性文本):

enter image description here

结果(iPhone 7,横向):

enter image description here

并且,同样的 View ,选择了一个表格行:

enter image description here

关于ios - 更改两个 UITableViewCells 之间的间距以匹配行间距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49558820/

相关文章:

ios - UITableView moveRowAtIndexPath 显示重复单元格

ios - Cordova 检测用户是否正在离开应用程序或开始通话(iOS)

ios - 当顶部 View 被点击时如何检测底部 View 的触摸位置

ios - Swift 中没有数据传递时的完成 block 语法

iOS:使用 MVC 实现 UITableView

ios - 仅重新加载自定义 UITableViewCell 的 subview

objective-c - 从数组元素属性获取对象时出错

ios - 与 AFIncrementalStore 的映射关系

swift - 在 Swift 中调试打印自定义类的“正确”方法

ios - 跳出 filter() 函数