【问题标题】:Add UILabels with different width side by side programmatically以编程方式并排添加不同宽度的 UILabel
【发布时间】:2017-06-06 13:00:23
【问题描述】:

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

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

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

【问题讨论】:

  • 您可以在您想要的每个位置添加标签。让 label = UILabel(frame: CGRect(x: 0, y: 0, width: 225, height: 25))。更改位置的 x 和 y
  • 但我的问题是标签的宽度不同。如何计算第三个标签不适合该行?
  • 视图的宽度是 375。所以一个标签的宽度是 150,另一个是 225。第三个标签放在第一个标签下面。通过设置 y.
  • 根据您的要求使用它:- github.com/ali312/TLTagsControl
  • 检查我的答案@I.G.

标签: swift uitableview autolayout uilabel programmatically-created


【解决方案1】:

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

【讨论】:

  • 这对于这种情况以及你会使用什么 UICollectionView 布局来说太过分了。您将如何确定集合视图中单元格的宽度/高度。您是否建议使用动态调整自身的完整自定义 UICollectionView 布局?
  • 有道理,我喜欢。
【解决方案2】:

一开始你必须制作标签。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

        let label1 = UILabel(frame: CGRect(x: 5, y: 5, width: 100, height: 25))
        label1.text = "Label 1"
        let label2 = UILabel(frame: CGRect(x: 110, y: 5, width: 225, height: 25))
        label2.text = "Label 2"
        let label3 = UILabel(frame: CGRect(x: 5, y: 40, width: 100, height: 25))
        label3.text = "Label 3"
        let label4 = UILabel(frame: CGRect(x: 110, y: 40, width: 225, height: 25))
        label4.text = "Label 4"
        cell.addSubview(label1)
        cell.addSubview(label2)
        cell.addSubview(label3)
        cell.addSubview(label4)

    return cell
}

每个标签都有不同的宽度和不同的位置。你可以玩它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    相关资源
    最近更新 更多