swift - 以编程方式并排添加不同宽度的 UILabel

标签 swift uitableview autolayout uilabel programmatically-created

我想以编程方式将多个 UILabel 并排添加到 TableViewCell。 UILabels 有不同的宽度。

图片中的第一个单元格显示了问题,第二个单元格显示了我想做的事情。

在此示例中,我想将四个 UILabel 添加到 TableViewCell。但是 TableViewCell 的宽度小于 UILabel 的宽度。因此,我必须增加 CellHeight 并将下面的 UILabel 添加到其他 UILabel(如图中的第二个单元格)。

enter image description here

最佳答案

您应该将 UICollectionView 放在 UITableViewCell 的一行中。 UICollectionView 的每个单元格都有一个多 UILabel。根据标签计数更新 UICollectionView 的数据源。将 UICollectionViewisScrollEnabled 设置为 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/

相关文章:

swift - 在 iOS 13 之后,在 pdf 上导航文本框不再工作 - 使用 PDFKIT 似乎是手势问题

swift - 如何定义和使用 LLDB 用户变量?

ios - 具有两个自动布局标签的 TableView 单元格,在 UIViewController 中不显示所有行

ios - 动画:使用 Autolayout、Frame.Origin 和 Broken Constraints,还是第三种选择?

ios - 调度 UILocalNotification 导致用户界面滞后和延迟

SwiftUI 图像导致中止陷阱 6

ios - 在表格 View 中滚动自定义表格单元格时出错

iphone - 从 UITableViewCell 调用

ios - 在保留滚动行为的同时向 UITableView 添加空消息

ios - UITableViewCell 未在 "Live"中自动调整大小