ios - 我们可以在 UITableView 的一部分中快速实现部分吗?

标签 ios swift uitableview

假设有一个 UITableView 有 2 个部分 A 和 B。现在在两个部分中,要显示多个对象的详细信息,例如如果对象是汽车,则有多辆汽车,名称,颜色,里程要在对象中显示。那么,鉴于我们必须使用 UITableView 来实现它,如何以最佳方式解决这个问题呢?

我为 UITableView 提供了 2 个部分。然后,我将对象显示为部分内的行。然后,如果我只显示一个对象的 3 个细节,那么我将提供行数 3*(对象数)。以下代码是在 UITableViewCell 类中编写的,并从 UIViewController 调用,其中包含 UITableView 对象的数据源方法 cellForRowAt()

func configureSectionACellWith(indexPath: IndexPath, data: [Car]) {
   var row = indexPath.row
   row = row % 3
   switch row {
   case 0: carNameLabel.text = data[indexPath.row/3].name
   case 1: colorLabel.text = data[indexPath.row/3].color
   case 2: mileageLabel.text = data[indexPath.row/3].mileage
   default:
       break
   }
}

同样,对于Section B的cells的配置,重复上面的代码。

但是您可能会看到,很多东西都是硬编码的,比如 row = row % 3,新开发人员很难理解这些代码。也有重复的代码(配置 A 和 B 部分的单元格)。 有没有其他方法当然是解决这种情况的最佳方法?

最佳答案

如果每个部分的布局/细节可能相同,您可以只创建一种类型的单元格并在两个部分中使用它:

class DetailCell: UITableViewCell {
  static let cellID = "DetailCell"
 //set up all the images/labels etc

  func configure(with car: Car) {
    label1.text = car.name
    label2.text = car.color
    label3.text = car.mileage
  }
  func configure(with other: SomeOtherType) {. //whatever Section B displays
    label1.text = other.property1
    label2.text = other.property2
    label3.text = other.property3
  }
}

您无需担心单元格定义的索引路径或行。这是在数据源和委托(delegate)函数中完成的。

您将使用 UITableViewDataSourcenumberOfRows 方法设置每个部分的行数,并在 cellForRowAt 中创建所有单元格方法。我不会在这里重复所有细节 - 有 100 多篇关于 tableView 的教程和博客 - 但会为您提供摘要示例,以便您了解您的目标:

override func viewDidLoad() {
   super.viewDidLoad()
   tableView.register(DetailCell.self, forCellReuseIdentifier: DetailCell.cellID)
   //any other setup
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   switch section :
   case 0: return carsArray.count //if you're showing cars in section A
   case 1: return someOtherArray.count //whatever you;re showing in section B
   default: return 0
   }
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
   let cell = tableView.dequeueReusableCell(withIdentifier: DetailCell.cellID, for: indexPath)
  if indexPath.section == 0 {
    cell.configure(with: carsArray[indexPath.row])
  } else if section == 1 {
    cell.configure(with: someOtherArray[indexPath.row])
  }
  //do any further cell set up
  return cell
}

关于ios - 我们可以在 UITableView 的一部分中快速实现部分吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58650331/

相关文章:

html - 替换网页中的 'non-tagged'内容

ios - 在 iOS 上重置模拟器后,我第一次运行 Cucumber 时应用程序崩溃

ios - 无法将 UIImageView 拖到 UIScrollview 的末尾?

swift - 此类不符合键名的键值编码。

ios - 如何根据表格行设置动态表格高度?

ios - UITableViewCell 中的 NSLayoutConstraint 使应用程序崩溃

ios - 使用 swift 的 DestinationViewController Segue 和 UINavigationController

ios - 设置 CIFiltered UIImage 时 UIImageVIew 崩溃

ios - 键盘处理就像在 iOS 7 中的消息应用程序中一样

iphone - 表格 View 无法正确加载