我想以编程方式将多个 UILabel 并排添加到 TableViewCell。 UILabels 有不同的宽度。
图片中的第一个单元格显示了问题,第二个单元格显示了我想做的事情。
在此示例中,我想将四个 UILabel 添加到 TableViewCell。但是 TableViewCell 的宽度小于 UILabel 的宽度。因此,我必须增加 CellHeight 并将下面的 UILabel 添加到其他 UILabel(如图中的第二个单元格)。
最佳答案
您应该将 UICollectionView
放在 UITableViewCell
的一行中。
UICollectionView
的每个单元格都有一个多 UILabel
。根据标签计数更新 UICollectionView 的数据源。将 UICollectionView
的 isScrollEnabled
设置为 false,并为 UITableViewCell
设置自动行高。
此外,将流布局设置为 UICollectionView
:
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.estimatedItemSize = CGSizeMake(1, 1) }
像下面这样调整单元格大小:
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let size: CGSize = keywordArray[indexPath.row].size(attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14.0)])
return CGSize(width: size.width + 45.0, height: keywordsCollectionView.bounds.size.height)
}
关于swift - 以编程方式并排添加不同宽度的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44390718/