代码之家  ›  专栏  ›  技术社区  ›  pheedsta

UITableViewCell具有不确定数量的UIImageViews

  •  1
  • pheedsta  · 技术社区  · 7 年前

    我想创建如下的UITableViewCells:

    enter image description here

    正如你所看到的,每个单元格都是为不同的朋友,它为他们的每只狗显示了一张图片(这是一个虚构的示例,仅用于演示目的)。每个人可能有零到无限数量的狗。我希望所有信息都包含在一个单元格中,这样用户可以触摸该单元格将应用程序切换到下一个屏幕(注意第二个单元格是如何选择的)。因此,每个单元格都需要某种方式添加UIImageViews和UILabels,以适应不同数量的狗。每个单元格还需要返回UITableView的单元格高度。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Nicolas Miari    7 年前

    但是嵌套表肯定是 过度杀戮 . 如果你认为内部细胞无论如何都是不可选择或不可交互的,那么。。。

    • 标题标签,以及
    • UIStackView ,

    ...在运行时向其中添加(可变)数量的堆叠子视图(类型 DogView

    你仍然需要让你的细胞高度可变,但有很多代码和答案告诉你如何实现这一点。

        2
  •  1
  •   pheedsta    7 年前

    1. 创建名为DogView的NIB。具有UIImageView(imageView)和UILabel(label)的XIB。 DogView.XIB

    2. 在tableView中注册StackCell,并在UITableViewDataSource中使用以下代码:

      override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
          let stackCell = tableView.dequeueReusableCell(withIdentifier: "StackCell", for: indexPath) as! StackCell
      
          // need to remove any previous views added to UIStackView (cell may have been dequeued)
          for view in stackCell.stackView.arrangedSubviews {
              view.removeFromSuperview()
          }
      
          // create label for friend's name
          let friendLabel = UILabel()
          friendLabel.font = UIFont.boldSystemFont(ofSize: UIFont.labelFontSize)
          friendLabel.text = friendName
          stackCell.stackView.addArrangedSubview(friendLabel)
      
          // add dog views for each dog
          for dog in friendsDogArray {
              guard let dogView = Bundle.main.loadNibNamed("DogView", owner: nil, options: nil)?.first as? DogView else {
                  continue
              }
      
              dogView.label.text = dog.name
              dogView.imageView.image = dog.image
              stackCell.stackView.addArrangedSubview(dogView)
          }
      
          return stackCell
      }
      

    这个解决方案的最大优点是,单元格高度是自动计算的,无需任何额外编码!